繁体   English   中英

excel vba中的引用变量名称

[英]reference variable name in excel vba

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

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

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

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

执行此操作的唯一方法是在模块级别声明所有变量,然后使用一个函数将变量名称显式映射到这些变量:

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

这适用于Excel 2010

variable1 = [variable1].Value

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

-mmh

暂无
暂无

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

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