我正在尝试创建一个允许我输入位置编号的函数,结果将为我提供一个唯一的位置代码。问题是我希望所有引用都在宏代码内部完成,而不是从电子表格中的某处获取信息。 (此代码将插入到外接程序中,因此没有要引用的工作表)。我基本上想在代码中而不是在工作表中执行vlookup。
我一直无法找出方法,下面的代码类似于我想要的东西,我在想也许使用数组,但我不知道如何使用它我想要。
我知道这是行不通的,但我正在尝试以下操作,以便当我输入=GetCode(415)
时结果为001
Function GetCode(LocationNum As String) As String
Dim Result As String
'Built in reference table
'
'{ "415" : "001"
' "500" : "002"
' "605" : "003"
' }
Dim varData(2) As Variant
varData("415") = "001"
varData("500") = "002"
varData("605") = "003"
LocationNum = varData("415")
Result = LocationNum
GetCode = Result
End Function
正如Nathan_Sav已经提到的,您可以改用集合或字典,这样会更加高效。这是使用字典对象的示例。请注意,它使用早期绑定,因此您需要设置对Microsoft脚本运行时库(Visual Basic Editor >> Tools >> Reference)
的引用。
Option Explicit
Sub test()
'set a reference (VBE >> Tools >> Reference) to the Microsoft Scripting Runtime library
'declare and create an instance of the dictionary object
Dim dic As Scripting.Dictionary
Set dic = New Scripting.Dictionary
'set the comparison mode for the dictionary to a case-insensitive match
dic.CompareMode = TextCompare
'add keys and associated items to the dictionary
dic.Add Key:="415", Item:="001"
dic.Add Key:="500", Item:="002"
dic.Add Key:="605", Item:="003"
'print to the immediate window the item associated with the specified key
Debug.Print dic("415")
'clear from memory
Set dic = Nothing
End Sub