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

时间:2014-02-14 08:06:59

标签: excel vba 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

我的问题是,如何获得split函数返回的数组大小(arr_size),以便我可以在for循环中使用?谢谢。

3 个答案:

答案 0 :(得分:15)

使用LBoundUbound

进行考虑
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

Btw Split始终返回从零开始的数组(从0开始,但不从1开始)。这就是为什么我建议你同时使用Ubound和Lbound。

还有一件事,我已将Dim last_cell As Integer更改为Dim last_cell As Long,因为Integer的最大值仅为32767,如果是最后一行如果大于32767,则Integer会出错。

avoid using Select/Active statements(约为Worksheets(3).Activate

答案 1 :(得分:2)

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'

答案 2 :(得分:2)

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

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