Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 创建字符串数组,作为参数发送给接受字符串的函数_Arrays_Excel_Vba_String - Fatal编程技术网

Arrays 创建字符串数组,作为参数发送给接受字符串的函数

Arrays 创建字符串数组,作为参数发送给接受字符串的函数,arrays,excel,vba,string,Arrays,Excel,Vba,String,我试图弄清楚如何声明和使用字符串数组。我到处都看到,建议使用variant类型的数组。为什么我不能创建一个只包含字符串的数组 我有一个函数,它接收一个字符串作为参数,我需要用6个不同的字符串调用这个函数6次。在这种情况下,最好使用字符串数组并在其上循环,每次使用正确的字符串调用函数。我如何声明这样的数组并访问它? 如果我声明了一个变量数组,我会得到一个类型不匹配错误,因为我的函数需要一个字符串 谢谢 更具体地说,我就是这么做的: dim strings() as variant dim i as

我试图弄清楚如何声明和使用字符串数组。我到处都看到,建议使用variant类型的数组。为什么我不能创建一个只包含字符串的数组

我有一个函数,它接收一个字符串作为参数,我需要用6个不同的字符串调用这个函数6次。在这种情况下,最好使用字符串数组并在其上循环,每次使用正确的字符串调用函数。我如何声明这样的数组并访问它? 如果我声明了一个变量数组,我会得到一个类型不匹配错误,因为我的函数需要一个字符串

谢谢

更具体地说,我就是这么做的:

dim strings() as variant
dim i as integer
dim res as integer
strings = Array ("string1", "string2", "string3")

For i = LBound(strings) To UBound(strings)
   res = MyFunction( strings(i))
Next


MyFunctions(str as string) as integer
'do something
end function

这会得到一个编译器错误:ByRef参数类型不匹配,而不是上述建议:

调用同一个函数6次不是问题,但是如果总是处理一个字符串数组,那么传入一个数组也不会有什么坏处

Sub subTest()

    Dim arrStrings() As String

    For i = 1 To 6
        ReDim Preserve arrStrings(1 To i)       '   Extend the array - 'preserve' retains the old values too
        arrStrings(i) = "this is string " & i
    Next i

    For Each strValue In arrStrings
        Debug.Print (strValue)                  '   Just so we see each string
    Next strValue

    Debug.Print (fncDoSomething(arrStrings))    '   Passing string array as parameter

End Sub
                                                '   Example function which counts how many characters are in your array.
Function fncDoSomething(ByRef strings() As String) As Integer    '   ByRef is important when passing an array.

    Dim intCharCount As Integer
    Dim strValue As Variant
    intCharCount = 0

    For Each strValue In strings
        intCharCount = intCharCount + Len(strValue)
    Next strValue

    fncDoSomething = intCharCount

End Function

除了一些语法错误外,还通过引用将变量类型传递给需要字符串的函数

这可以通过强制VBA将表达式转换为字符串来克服:

Sub Button1_Click()
Dim strings() As Variant
Dim i As Integer
Dim res As Integer
strings = Array("string1", "string2", "string3")

For i = LBound(strings) To UBound(strings)
   res = MyFunction((strings(i)))
Next

End Sub

Function MyFunction(str As String) As Integer
Debug.Print str
End Function
通过在正在传递的参数周围放置一组额外的括号

参考: