0

※本题是下题的续题

如何在excel vba中为矩阵单元格使用嵌套循环

我想传递动态数组(参数),我在下面尝试,但它不能正常工作。请你帮助我好吗。

    Dim StartrowArr, Startrow1Arr, J As Integer
    Dim flRow, dtRow As String

    Set filRng = Worksheets("Sheet1").Range("C1:C50")
    Set dtlRng = Worksheets("Sheet1").Range("F1:F50")

    For Each cell In filRng
        If cell.Value <> "" Then
            ftRow = ftRow & cell.Row & ","
        End If
    Next cell
    ftRow = Left(ftRow, Len(ftRow) - 1)
    Debug.Print ftRowNo

    For Each cell In dtlRng
        If cell.Value <> "" Then
            dtRow = dtRow & cell.Row & ","
        End If
    Next cell
    dtRow = Left(dtRow, Len(dtRow) - 1)
    Debug.Print dtRow

    StartrowArr = Array(filRowNo) ※ dynamic array args
    Startrow1Arr = Array(dtlRowNo)

但是在像上面那样初始化 Array(args) 之后,它在 [Startrow1, init with 0] 上返回错误 1004。我还尝试使用 CInt(ftRow) 从字符串类型转换为整数。什么都没有改变。
此外,日志显示 Startrow、Startrow1 的值如下所示。

    Startrow: 2, 4, 7
    Startrow1: 2611 ※ should be 2, 6, 11

但是,如果我静态初始化 StartrowArr = Array(2,4,7)。它完美无缺。
如何将参数正确传递给 StartrowArr 和 Startrow1Arr。

4

1 回答 1

0

要制作动态数组,请使用redim preserve

Sub test()
    Dim StartrowArr(), Startrow1Arr(), J As Integer
    Dim flRow, dtRow As String
    Dim Cell As Range
    Dim k As Long, n As Long

    Set filRng = Worksheets("Sheet1").Range("C1:C50")
    Set dtlRng = Worksheets("Sheet1").Range("F1:F50")

    For Each Cell In filRng
        If Cell.Value <> "" Then
            'ftRow = ftRow & cell.Row & ","
             ReDim Preserve StartrowArr(k)
             StartrowArr(k) = Cell.Row
             k = k + 1
        End If
    Next Cell
    'ftRow = Left(ftRow, Len(ftRow) - 1)
    Debug.Print Join(StartrowArr, ",")

    For Each Cell In dtlRng
        If Cell.Value <> "" Then
            'dtRow = dtRow & Cell.Row & ","
             ReDim Preserve Startrow1Arr(n)
             Startrow1Arr(n) = Cell.Row
             n = n + 1
        End If
    Next Cell
    'dtRow = Left(dtRow, Len(dtRow) - 1)
    Debug.Print Join(Startrow1Arr, ",")

    'StartrowArr = Array(mapRowNo) '※ dynamic array args
    'Startrow1Arr = Array(tcRowNo)
End Sub
于 2017-08-04T02:49:28.187 回答