【问题标题】:Create reference table or array inside of the code在代码内部创建引用表或数组
【发布时间】:2020-03-06 16:11:46
【问题描述】:

我正在尝试创建一个允许我输入位置编号的函数,结果会给我一个唯一的位置代码。问题是我希望在宏代码内完成所有引用,而不是从电子表格中的某个位置获取信息。 (此代码将进入加载项,因此没有工作表可供参考)。我基本上想做一个 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"

  Result = varData(LocationNum)

  GetCode = Result

  End Function

【问题讨论】:

标签: arrays excel vba reference


【解决方案1】:

正如 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

【讨论】:

    猜你喜欢
    • 2014-07-12
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多