我想在声明新变量时访问字符串的值,这样我就可以在循环中声明新变量。
我尝试了val(),创建了一个函数。我的问题的简化版本可以在下面的代码中找到。
Function StudentValue(x As String) As String
StudentValue = x
End Function
Public Sub TEST()
Dim i As Integer
Dim strName As String
Dim n As Integer
n = 20
For i = 1 To n
strName = "Variable" & CStr(i)
'The problem occurs with the next two lines,
'once active they create a string with the name 'strName' and not the
'value of the string eg 'Variable1', 'Variable2', ect
'Attempt1
'Dim strName As String
'Attempt2
'Dim NameFunction(strName) As String
Next i
End Sub
错误如下:
Dim strName As String results in "compile error: Duplicate declaration in current scope"
Dim NameFunction(strName) As String results in "compile error: Constant expression required"
有没有一个函数可以让你在声明变量时访问字符串的值?
提前谢谢你!
发布于 2019-06-27 12:24:22
你得到了“重复声明”错误,因为你试图用相同的名称声明一个变量。
因为Dim XYZ() as string是用于声明数组的语法,所以会出现错误"Constant expression required“错误。括号内的值指定数组的大小,并且必须是常量。
Here is a link on how to use arrays.
使用Option Explicit,它将帮助你在问题出现之前解决问题。
这是使用数组的代码。
Option Explicit
Function StudentValue(x As String) As String
StudentValue = CStr(x)
End Function
Public Sub TEST()
Const MaxNumNames As Integer = 20
Dim i As Integer
Dim strNames(1 To MaxNumNames) As String
For i = 1 To MaxNumNames
'This will populate the array of names
strNames(i) = "Variable" & CStr(i)
'To use the name in the loop
Debug.Print "In Loop:" & strNames(i)
Next i
'To use the name outside the loop (Show 5th name)
Debug.Print "Outside Loop: " & strNames(5)
' To use the name in your function outside the loop (Using 2nd Name)
Debug.Print "Using Function: " & StudentValue(strNames(2))
End Sub
https://stackoverflow.com/questions/56790453
复制