2017-03-10 349 views
0

我在Excel中的VBA代碼有問題。 我的表格由幾個不同長度的列組成。在這些列的前面,我想顯示塊的實際ID(而不是問題)。 問題是,實際ID只出現在塊的第一行,因此每個塊ID下都有一定數量的空單元。在VBA中填充空單元格

我發現了一個代碼,我可以填充這些空單元與實際塊ID:

Sub Leere_auffuellen() 
    With Worksheets(3).Range("A5:A1000") 
     If Application.WorksheetFunction.CountBlank(Intersect(.Cells, .Parent.UsedRange)) > 0 Then 
      .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C" 
      .Value = .Value 
     End If 
End Sub 

這適用於最長的柱。我的問題是,我也想爲較短的欄目做到這一點。如果我使用上面的代碼,它將使用ID填充行,直到達到最長行的長度。 如何調整代碼以使其引用我想要的列?

我希望你們明白我想

+0

你告訴你的代碼從5行中列A運行到1000什麼('範圍( 「A5:A1000」)' )。相反,首先嚐試獲取實際的行數(看[這裏](http://stackoverflow.com/a/71310/1726522)),然後相應地定義範圍。你也可能想要添加一個循環來處理很多列。 – CMArg

回答

0

試試這個

Sub Leere_auffuellen() 

Dim x As Long 
Dim LastRow As Long 
Dim LastCol As Long 
Dim DataStarted As Boolean 
DataStarted = False 

'Activate target worksheet. 
Worksheets(3).Activate 
'Find the last row with data. 
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 

For x = 1 To LastRow 
    'Don't do anything until the first time a non-blank cell in column A is reached. 
    If Cells(x, 1) <> "" Then 
     DataStarted = True 
    'Then if there are blanks in the row, fill them in with the data from the cell above. 
    ElseIf DataStarted Then 
     LastCol = Rows(x - 1).Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 
     With Range(Cells(x, 1), Cells(x, LastCol)) 
      .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C" 
      .Value = .Value 
     End With 
    End If 
Next x 

End Sub 
相關問題