2017-08-04 58 views
0

※這個問題的以下問題如何分析動態數組參數在Excel VBA中的可變

How to use nested loop for a Matrix cell in 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) 

但初始化陣列(參數)等上面之後,它返回錯誤1004 [Startrow1在初始化與0]。我也嘗試過CInt(ftRow)來從字符串類型轉換爲Integer。沒有改變。
此外,日誌顯示Startrow,Startrow1的值如下。

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

但是,如果我靜態初始化StartrowArr = Array(2,4,7)。它工作完美。
如何正確地將參數傳遞給StartrowArr和Startrow1Arr。

+0

什麼是你傳遞給Array()的mapRowNo和tcRowNo? –

回答

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 
+0

謝謝你Dy Lee。太棒了。完美的工作。
我也在嘗試幾乎非常接近您的解決方案,但無法正確處理我的代碼並搞砸了。 – DIO