将参数传递给函数以创建变量名

时间:2019-11-06 16:19:09

标签: excel vba user-defined-functions

我希望能够在我的工作簿中使用一些全局变量,并在ThisWorkbook代码中声明了以下变量

Public position_1 as string
Public position_2 as string

如果我想查看这些变量的值,我认为需要完全限定

Debug.Print ThisWorkbook.position_1
Debug.Print ThisWorkbook.position_2

我写了一个UDF,它将传递一个整数来表示我要寻找的变量。我只会传递一个数字,而不是完整的变量名。我正在尝试找到一种使用此Integer与“ position_”连接以显示全局变量ThisWorkbook.position_1,ThisWorkbook.position_2等的值的方法。

这可能吗?

 Function Test_Global_Var(position as Integer)
            Dim variable_name As String
            variable_name = "position_" & position
            Debug.Print ThisWorkbook.variable_name
        End Function

所以我打电话给

Test_Global_Var(1) 

我的即时窗口应显示

的值
ThisWorkbook.position_1

2 个答案:

答案 0 :(得分:0)

可以考虑全局字典变量,并从UDF通过它传递数据。 首先添加对Microsoft脚本运行时的引用:

enter image description here

因此,像这样构建字典:

Public myDictionary As Dictionary

要初始化myDictionary变量,请考虑将其添加到Workbook_Open事件中:

Private Sub Workbook_Open()
    Set myDictionary = New Dictionary
End Sub

然后,UDF将如下所示:

Public Function FillDicitonary(myVal As Long) As String

    If myDictionary.Exists(myVal) Then
        myDictionary(myVal) = "position " & myVal
    Else
        myDictionary.Add myVal, "position " & myVal
    End If
    FillDicitonary = "Filled with " & myVal

End Function

如果存在,它将覆盖字典中的每个键。最后,可以打印这些值:

Public Sub PrintDictionary()

    Dim myKey As Variant
    For Each myKey In myDictionary
        Debug.Print myDictionary(myKey)
    Next

End Sub

答案 1 :(得分:0)

下面的代码产生以下调试输出

2 values defined.
ThisWorkbook.Position(0)
First Value
ThisWorkbook.Position(1)
Second Value

它在名为m_position的工作簿中使用私有数组。内容由全局属性ThisWorkbook.Position(index)访问。

模块中,具有以下代码:

Option Explicit

Public Sub Test()    
    If ThisWorkbook.NoValues Then
        ThisWorkbook.FillValues "First Value", "Second Value"
    End If

    Debug.Print CStr(ThisWorkbook.Count) & " values defined."

    Test_Global_Var 0
    Test_Global_Var 1
End Sub

Public Sub Test_Global_Var(ByVal index As Long)
    ' Part of a UDF
    Debug.Print "ThisWorkbook.Position(" & CStr(index) & ")"
    Debug.Print ThisWorkbook.Position(index)

End Sub

此工作簿中,具有以下代码:

Option Explicit

Private m_position() As Variant

Private Sub Workbook_Open()
    Call DefaultValues
End Sub


Public Property Get Position(ByVal index As Long) As Variant
    Position = m_position(index)
End Property

Public Sub DefaultValues()
    m_position = Array("First", "Second")
End Sub

Public Sub FillValues(ParamArray args() As Variant)
    m_position = args
End Sub

Public Property Get Count() As Long
    Count = UBound(m_position) - LBound(m_position) + 1
End Property

Public Property Get NoValues() As Boolean
    On Error GoTo ArrUndefined:
    Dim n As Long
    n = UBound(m_position)
    NoValues = False
    On Error GoTo 0
    Exit Sub
ArrUndefined:
    NoValues = True
    On Error GoTo 0
End Property

PS。在VBA中,请勿使用Integer,而应使用LongInteger是16位类型,而Long是其他所有编程语言都认为是integer的标准32位类型。