2016-12-20 142 views
0

我的宏經歷了一個範圍,按列循環,找到數字數據在每列開始的位置,並將範圍存儲在鋸齒陣列(代碼中的「矩陣」變體)中。VBA鋸齒陣列到範圍

之後,我想將整個矩陣返回到另一個工作表中的範圍。如果我試圖將「矩陣(1)」分配到我希望放置的範圍內,它可以正常工作,但是如果我嘗試將整個「矩陣」分配給一個範圍,則會得到空白單元格。

如何在不使用循環的情況下一次將「矩陣」中的所有值返回到一個範圍?

這是源數據,通過這些代碼循環: enter image description here

我想所有的「矩陣」的行會,因爲這會返回: enter image description here

這裏是我的代碼:

 Sub MyMatrix() 

     Dim wb1 As Workbook 
     Set wb1 = ActiveWorkbook 

     Dim wsNSA As Worksheet 
     Set wsNSA = wb1.Worksheets("NSA") 

     Dim wsSA As Worksheet 
     Set wsSA = wb1.Worksheets("SA") 

     Dim col As Range 

     Dim matrix() As Variant 


     'LR is the Last row and LC is the last column with data 
     LR = wsNSA.Cells(1, 1).End(xlDown).Row 
     LC = wsNSA.Cells(LR, 1).End(xlToRight).Column 

     'Loops through columns and finds the row where numeric data begins 
     For Each col In wsNSA.Range(wsNSA.Cells(1, 2), wsNSA.Cells(LR, LC)).Columns 
     wsNSA.Activate 
     nsa = wsNSA.Range(wsNSA.Cells(1, col.Column), wsNSA.Cells(LR, col.Column)) 

     num_linha = Application.Match(True, Application.Index(Application.IsNumber(nsa), 0), 0) 
     nsa = wsNSA.Range(wsNSA.Cells(num_linha, col.Column), wsNSA.Cells(LR, col.Column)) 

    'The range starts in the column B in the worksheet, so the matrix ubound is 'col.column -1 
     ReDim Preserve matrix(1 To col.Column - 1) 
     matrix(col.Column - 1) = nsa 

     Next 

     wsSA.Range(wsSA.Cells(3, 2), wsSA.Cells(LR, LC)) = matrix 


     End Sub 
+1

如果是參差不齊的,最好的辦法可能是遍歷行,分配各行的範圍在一個單一的聲明。 –

+2

你是否在使用'matrix'做任何事情,而不是將它用作值的臨時存儲?如果沒有,那麼'ReDim Preserve'聲明幾乎肯定比將每行轉儲到循環中的'wsSA'更加昂貴。 –

+0

您希望輸出在返回時看起來如何?您是否希望將每個源列中的第一個數字項目放置在目標的第3行中,還是希望每行源信息作爲目標中的一行返回(但將前導非數字單元格設置爲空白)?也許更新你的問題,包括你的源數據和預期輸出的屏幕轉儲。 – YowE3K

回答

0

如果你願意忘記輸出不應該被寫入循環的要求,下面的代碼可能會做你正在做的事情英做:

Sub MyMatrix() 

    Dim wb1 As Workbook 
    Set wb1 = ActiveWorkbook 

    Dim wsNSA As Worksheet 
    Set wsNSA = wb1.Worksheets("NSA") 

    Dim wsSA As Worksheet 
    Set wsSA = wb1.Worksheets("SA") 

    Dim c As Long 
    Dim LC As Long 
    Dim LR As Long 
    Dim num_linha As Long 
    Dim nsa As Variant 

    With wsNSA 
     'LR is the Last row and LC is the last column with data 
     '???? Is data1_linha declared anywhere and assigned a value? ???? 
     LR = .Cells(data1_linha, 1).End(xlDown).Row 
     LC = .Cells(LR, 1).End(xlToRight).Column 

     'Loops through columns and finds the row where numeric data begins 
     For c = 2 To LC 
      nsa = .Range(.Cells(1, c), .Cells(LR, c)) 
      num_linha = Application.Match(True, Application.Index(Application.IsNumber(nsa), 0), 0) 
      wsSA.Cells(3, c).Resize(LR - num_linha + 1, 1).Value = .Range(.Cells(num_linha, c), .Cells(LR, c)).Value 
     Next 
    End With 

End Sub 
1

你可以複製所有後刪除空白單元格:

Sheet1.Range("A3").CurrentRegion.Copy Destination:= Sheet2.Range("A3") 

Sheet2.Range("A3").CurrentRegion.SpecialCells(xlCellTypeBlanks).Delete xlShiftUp