【问题标题】:reference variable name in excel vbaexcel vba中的引用变量名
【发布时间】:2013-08-22 13:27:18
【问题描述】:

我在电子表格列中有大量变量名称。这些变量在我的项目中的模块中定义并具有值。

我想要一个引用电子表格中的变量名的代码,并返回它在模块中的值并将该值粘贴到另一个电子表格中,即

Sub code()

    dim variable1 as integer
    variable1 = 2 

End sub

sheet 1: cell A1: variable1

Sub code2()
    sheet(2).range("a1").value = sheet(1).range("a1").value
end sub

sheet 2: cell A1: 2

【问题讨论】:

  • 当您描述“电子表格列中的变量名称”时,您的问题不清楚。这是什么意思?它看起来怎么样?
  • column a: variable1, variable2, variable3,在a1,a2,a3中分别是‘变量名’,这些变量都有值。即 1,2,3 从模块中取出,在一个子过程中。我想要一个在电子表格中查找这些变量名称并返回值的代码...
  • 还是有点不清楚。但是,另外您可以尝试以这种方式命名您的单元格,Sheet1、单元格 A1 将具有 variable1 名称。接下来,您将需要使用以下参考来检查/设置其值:Sheets("Sheet1").Range("Variable1").Value。但是你不能这样做:Sheets("Sheet1").Range(Variable1).Value。或者,检查 VlookUp 函数是否不是您要查找的函数。

标签: excel vba


【解决方案1】:

在运行时无法在 VBA 中按名称请求变量。在编译期间,所有变量名都被删除,并且在运行时仅使用内存位置引用变量。此外,如果变量在子程序中声明,则它仅在执行该子程序时存在。如果您稍后尝试访问它,其他东西将使用它的内存位置。

这样做的唯一方法是在模块级别声明所有变量,然后有一个函数显式将变量名映射到这些变量:

Private variable1 As Integer

Sub code()
    variable1 = 2
End Sub

Sub code2()
    Sheets(2).Range("a1").Value = VariableByName(Sheets(1).Range("a1").Value)
End Sub

Function VariableByName(VarName As String) As Variant
    Select Case VarName
        Case "variable1": VariableByName = variable1
    End Select
End Function

实际上,您最好的选择是忘记使用变量并改用名称:

Sub code()
    Names.Add "variable1", 2, Visible:=False
End Sub

Sub code2()
    Sheets(2).Range("a1").Value = Evaluate(Sheets(1).Range("a1").Value)
End Sub

但是当你走这条路时,如果你需要访问 VBA 中的变量你不能只说variable1,你需要使用这样的代码:

Sub code3()
    Dim variable1 As Integer

    variable1 = Evaluate("variable1") 'bring it into a normal variable
    variable1 = variable1 * 2 'now you can use it like a normal variable
    Names("variable1").RefersTo = variable1 'need to save it when you're done
End Sub

【讨论】:

    【解决方案2】:

    这在 Excel 2010 中有效

    variable1 = [variable1].Value
    

    VBA 将 [variable1](带括号)视为引用命名单元格的变体。

    -mmh

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2019-01-20
      • 2011-11-16
      相关资源
      最近更新 更多