我是VBA的新手,正在尝试将字符串从Sub传递到公共功能(Sub和Public Function在单独的模块中,但在同一工作簿中),将字符串拆分为Public Function中的数组,然后将数组从Public Function传递回Sub。
我已经搜索了Stack Overflow,并尝试了几种不同的方法,但是它们没有用。下面是我目前拥有的代码,它会产生以下错误:
运行时错误“ 9”: 下标超出范围
任何帮助将不胜感激。道歉的基本问题。谢谢。
子:
Date Name Num
oct1 Test 5
oct2 Apple 7
在另一个模块中调用以下公共功能:
Sub export()
Dim testString As String
Dim testValue As Variant
'testString could have any number of values
testString = "TEST1, TEST2, TEST3, TEST4"
'Call the Public Function below
testValue = splitText(testValue)
End Sub
答案 0 :(得分:2)
您需要使用一致的变量名并在函数调用中传递参数
Public Sub export()
Dim testString As String
Dim testValue As Variant
testString = "TEST1, TEST2, TEST3, TEST4"
testValue = splitText(testString) '<== consistent naming and passed as argument
End Sub
Public Function splitText(ByVal testString As String) As Variant '<== argument referenced in function signature
Dim testValue As Variant
testValue = Split(testString, ",") '<== consistent naming
splitText = testValue
End Function