2016-03-17 58 views
1

我有一個工作表,每個其他列填充數字1-9,從不同的行開始。我編寫了以下子文件,在每列中填充的單元格右側的單元格中填充「Test [number]」。使用數組來填充相鄰的單元格

我遇到了兩個不同的問題,我無法弄清楚。請參閱下面的示例之前和之後的截圖。

1 H列的值在第1行開始,但代碼開始於行人口2

2.將所得的無「試驗[數字]」細胞晃過列9

代碼:

Sub test() 

Dim i As Long 
Dim j As Long 
Dim c As Long 
Dim r As Long 
Dim rng As Range 
Dim crng As Range 
Dim carr() As Variant 
Dim rarr() As Variant 

With ThisWorkbook.ActiveSheet 
c = .Cells(1, 1).SpecialCells(xlCellTypeLastCell).Column 
For j = 1 To c 
If Not Columns(j).Find(what:="*", after:=Columns(j).Cells(1, 1), LookIn:=xlValues) Is Nothing And Columns(j).Find(what:="test", after:=Columns(j).Cells(1, 1), LookIn:=xlValues) Is Nothing Then 
    r = Columns(j).Find(what:="*", after:=Columns(j).Cells(1, 1), LookIn:=xlValues).Row 
    Set rng = .Range(.Cells(r, j), .Cells(.Rows.Count, j).End(xlUp)) 
    rarr = rng.Value 
For i = r To UBound(rarr, 1) 
    Cells(i, j + 1).Value = "test " & (i - r) + 1 
Next i 
End If 
Next j 

End With 

End Sub 

前: enter image description here

後: enter image description here

所需的結果: enter image description here

我是很新,在我的代碼使用數組,所以我也不會感到驚訝,如果我的方法是關閉的。這就是說,我很難過,UBound(rarr,1)不返回最後一個單元格rng = .Range(.Cells(r, j), .Cells(.Rows.Count, j).End(xlUp))

任何幫助或建議表示讚賞。

感謝

回答

2

H欄已開始第2行,因爲你問的Range.Find method開始after:=Columns(j).Cells(1, 1)。我已經改變了它在列中最後一個單元格後面開始,以便它回到頂部。

UBound(rarr,1)是數組的上邊界。 LBoundUBound函數返回下邊界和上邊界或數組。這是'rng內的位置,而不是工作表上的實際行。

Sub test() 

    Dim i As Long 
    Dim j As Long 
    Dim lc As Long 
    Dim lr As Long 
    Dim r As Long 
    Dim rng As Range 
    Dim crng As Range 
    Dim carr() As Variant 
    Dim rarr() As Variant 

    With ThisWorkbook.ActiveSheet 
     lc = .Cells(1, 1).SpecialCells(xlCellTypeLastCell).Column 
     lr = .Cells(1, 1).SpecialCells(xlCellTypeLastCell).Row 
     For j = 2 To lc Step 2 
      If CBool(Application.CountA(.Columns(j))) Then 
       r = .Columns(j).Find(what:="*", after:=.Cells(lr, j), LookIn:=xlValues).Row 
       Set rng = .Range(.Cells(r, j), .Cells(.Rows.Count, j).End(xlUp)) 
       rarr = rng.Value 
       For i = LBound(rarr, 1) To UBound(rarr, 1) 
        .Cells(i + (r - 1), j + 1).Value = "test " & i 
       Next i 
      End If 
     Next j 
    End With 

End Sub 

雖然你已經建立了一個With ... End With statement,它不是整個代碼用來表示父表。 Range.Cells,Range objectsRange.Columns中的每一個都必須使用前綴.以繼承.Parent工作表property.reference。

+0

這正是我試圖做。感謝您的詳細解釋 –

0

作爲所有這些常量(數字),我會建議對我們有Excel的工作......

Option Explicit 

    Sub test() 

     With ActiveSheet.Cells.SpecialCells(xlCellTypeConstants).Offset(, 1) 
      .FormulaR1C1 = "=CONCATENATE(" & """" & "test" & """" & "&" & "COUNT(R1C[-1]:RC[-1]))" 
      .Value = .Value 
     End With 

    End Sub 
相關問題