2017-03-10 362 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 
相关问题