excel 如何在VBA中通过字符串变量设置xldirection?

lymnna71  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(89)

我试图控制Range().End(xldirection)的搜索方向。如何用变量设置xldirection?

Dim D As Range
    Dim aa As String
    Set D = Range("$A$1")
    
    aa = "xldown"
    f = Range(D, D.End(aa))

我以为它能覆盖整个范围。

56lgkhnf

56lgkhnf1#

使用Enum eration

Dim aa As XlDirection
aa = xlDown

如果您特别使用String变量,那么一个选项是创建一个字典,将String表示Map到内置常量。

' Requires a reference to Microsoft Scripting Runtime
Static Function Directions() As Scripting.Dictionary
    Dim d As Scripting.Dictionary
    Set d = New Scripting.Dictionary
    
    d.Add "xlUp", xlUp
    d.Add "xlDown", xlDown
    d.Add "xlToLeft", xlToLeft
    d.Add "xlToRight", xlToRight
    
    Set Directions = d
End Function

Sub Whatever()
    Dim bb As String
    bb = "xlDown"
    
    Dim d As Range, f As Range
    Set d = Range("A1")
    
    Set f = Range(d, d.End(Directions(bb)))
End Sub

这里的Static关键字真的有点多余,但是它允许Directions中的d只被创建一次,并且只要程序在运行,它就可以保持它的值。它也可以是Static d As Scripting.Dictionary(这里是Static * 语句 *,而不是关键字)。更多信息请参见docs
或者使用Function

Public Function Direction(ByVal d As String) As XlDirection
    Select Case d
        Case "xlUp"
            Direction = xlUp
        Case "xlDown"
            Direction = xlDown
        Case "xlToLeft"
            Direction = xlToLeft
        Case "xlToRight"
            Direction = xlToRight
    End Select
End Function

相关问题