【问题标题】:Array Size Returned by Split Function - Excel VBA拆分函数返回的数组大小 - Excel VBA
【发布时间】:2014-03-13 11:47:22
【问题描述】:

这是我到目前为止所做的。

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 循环中使用?谢谢。

【问题讨论】:

标签: vba excel


【解决方案1】:

考虑使用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

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

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

还有avoid using Select/Active statements(大约是Worksheets(3).Activate

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:
      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'
      

      【讨论】:

      • 您能否详细解释一下您的答案?
      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多