简体   繁体   English

excel vba中的引用变量名称

[英]reference variable name in excel vba

I have a load of variable names in a spreadsheet column. 我在电子表格列中有大量变量名称。 These variables are defined and have values in the modules I have in my project. 这些变量已定义,并且在我的项目中的模块中具有值。

I want to have a code that references the variable name in a spreadsheet, and returns the value that it have in the module and pastes the value in another spreadsheet ie 我希望有一个代码在电子表格中引用变量名称,并返回它在模块中的值,并将值粘贴到另一个电子表格中,即

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

There is no way to ask for a variable by name in VBA during runtime. 在运行时期间无法在VBA中按名称请求变量。 During compilation all variable names are stripped away, and at runtime the variables are referenced just with memory locations. 在编译期间,所有变量名称都被删除,并且在运行时,变量仅使用内存位置引用。 Also, if the variable is declared within a sub, it only exists while that sub is being executed. 此外,如果变量在sub中声明,则在执行该sub 时才存在。 If you try to access it later, something else will be using its memory location. 如果您稍后尝试访问它,则其他内容将使用其内存位置。

The only way to do this is to declare all the variables at module level, and then have a function which explicitly maps variable names to these variables: 执行此操作的唯一方法是在模块级别声明所有变量,然后使用一个函数将变量名称显式映射到这些变量:

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

Actually, your best option is to forget about using variables and use names instead: 实际上,您最好的选择是忘记使用变量并使用名称:

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

But when you go that route, if you need to access the variable in VBA you can't just say variable1 , you need to use code like this: 但是当你走这条路线时,如果你需要在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

This worked in Excel 2010 这适用于Excel 2010

variable1 = [variable1].Value

VBA treats [variable1] (with brackets) as a variant that references the named cell. VBA将[variable1](带括号)视为引用指定单元格的变体。

-mmh -mmh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM