我真的很喜欢VBA(10小时)来自一些Python背景。在索引返回函数的一部分时,是否存在与Python等效的VBA?这就是我的意思: 如果我的VBA代码如下所示:
Split(Worksheets("range").Range("K2").Offset(i, 0), "-", "-1")
我只想要分裂的第三部分,我将如何获得输出?
我想这是一个非常简单的问题,但我似乎无法思考。提前谢谢!
答案 0 :(得分:1)
如果此函数正在设置变量/数组变量的值,例如:
Dim myArray as Variant
myArray = Split(Worksheets("range").Range("K2").Offset(i, 0), "-", "-1")
然后你应该能够引用数组中的第3项,如:
Debug.Print myArray(2) 'Option Base 0 -- Default'
或者,如果您有Option Base 1
则:
Debug.Print myArray(3)
这些示例使用常量表达式(2或3)来索引数组项。您还可以使用匹配函数返回动态值,例如,假设您在此数组中查找“Steve”的值:
Dim aItem as Long
aItem = Application.Match("Steve", myArray, False)
这将返回一个长整数,然后您可以引用它:
Debug.Print myArray(aItem)
干杯!
答案 1 :(得分:0)
类似的东西:
Dim splitArr() as String, Counter as Long
Dim textString as String
textString = Worksheets("range").Range("K2").Offset(i, 0).Value2
splitArr = split(textString,"-",-1)
For cntr = LBound(splitArr) To UBound(splitArr)
'here you can process splitArr(cntr)
Next cntr
' Just accessing the third element can be done by accessing splitArr(LBound(splitArr)+2)
请注意,根据您的设置,VBA中的数组从0开始或从1开始,上述代码适用于任何一种情况。另请注意,如果字符串为空,您可能需要捕获错误/最终会出现一个整数数组。