分割函数返回的数组大小 – Excel VBA

这是我迄今为止所做的。

Sub MP_division() Worksheets(3).Activate Dim last_cell As Integer Dim platforms() As String Dim arr_size As Integer platforms = Split(Cells(2, 47), ", ") last_cell = Mid(Range("A1048576").End(xlUp).Address, 4) arr_size = len(platforms) // is there something like this? For x = 1 To last_cell For y = 1 To arr_size //do something Next Next End Sub 

我的问题是,我怎么可能得到由分裂函数返回的数组大小(arr_size),以便我可以在我的for循环? 谢谢。

考虑大量使用LBound和Ubound :

 Sub MP_division() Dim last_cell As Long Dim platforms() As String Dim x As Long, y As Integer With ThisWorkbook.Worksheets(3) platforms = Split(.Cells(2, 47), ", ") last_cell = .Cells(.Rows.Count, "A").End(xlUp).Row For x = 1 To last_cell For y = LBound(platforms) To UBound(platforms) 'do something Next Next End With End Sub 

顺便说一句 , 拆分总是返回从零开始的数组(从0开始,但不是从1 )。 这就是为什么我build议你同时使用Ubound和Lbound。

还有一件事 ,我已经把Dim last_cell As Integer改成Dim last_cell As Integer Dim last_cell As Long ,因为Integer最大值只有32767 ,如果最后一行会大于32767 ,你将得到一个Integer错误。

避免使用Select / Active语句 (这是关于Worksheets(3).Activate

 Dim first as integer Dim last as integer Dim arr() as string Dim lengthOfArray as integer 'split your data and save it in arr' first = LBound(arr) last = UBound(arr) lengthOfArray = last - first msgbox lengthOfArray 'This will display the length of the array' 

VBA LBound和UBound返回第一个和最后一个数组的位置,所以正确答案是:

 size = UBound(myArray) - LBound(myArray) + 1