在循环中定义时如何访问字符串的值

时间:2019-06-27 11:56:37

标签: excel vba

在声明新变量时,我想访问字符串的值,以便可以在循环中声明新变量。

我尝试使用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"

是否有一个函数可以让您在声明变量时访问字符串的值?

提前谢谢!

1 个答案:

答案 0 :(得分:3)

由于尝试用相同的名称声明变量,因此出现“重复声明”错误。
您将收到错误“需要常量表达式”错误,因为Dim XYZ()作为字符串是声明数组的语法。并且方括号内的值指定了数组的大小,并且必须为常数。

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