我有下表:
Code Year
8948KH 2003
2004
2005
2006
923587 2003
2004
2005
2006
938972 2003
2004
2005
2006
假设“Code”在单元格A1中。我想要8948KH,923587和938972的值复制/粘贴自己,直到它们遇到另一个代码。
为此,我使用了以下代码。我在D Mason制作的Stackoverflow上找到了:
Sub replaceBlanks()
' define variables
Dim column As Integer
Dim row As Integer
Dim lastRow As Integer
Dim previousValue As String
Dim value As String
' stop screen from updating to speed things up
Application.ScreenUpdating = False
' use the active sheet
With ActiveSheet
' get the current cell selected and the last row in column selected
column = ActiveCell.column
row = ActiveCell.row
lastRow = .Cells(.Rows.Count, column).End(xlUp).row
' set previous value to the first cell
previousValue = Cells(row, column).value
' iterate for every row between selected and last row with data in
For i = row To lastRow
' set value = the content of that cell
value = Cells(i, column).value
' if it contains nothing
If Len(value) < 1 Then
' set the value of cell equal to the previous cell that had something in it
Cells(i, column).value = previousValue
' if it contains something
Else
' update the previous value and move on to next row
previousValue = value
End If
Next i
End With
' update the screen at the end
Application.ScreenUpdating = True
End Sub
这适用于非常小的循环。但是,我需要循环大约6700行代码,分布在80.000行以上。在每个代码和下一个代码之间只有11个空行,我需要它们留在那里将代码复制到。
如果我尝试这样做,Excel会产生“运行时错误6溢出”并在调试器中引用lastRow = .Cells(.Rows.Count, column).End(xlUp).row
。
有没有办法调整宏以防止Excel产生错误?
答案 0 :(得分:0)
尝试这个更整洁的替代方案。
Sub Fill_in_the_Blanks()
With Cells(1, 1).CurrentRegion.Columns(1)
.SpecialCells(xlCellTypeBlanks).Formula = "=A2"
.Cells.Value = .Cells.Value
End With
End Sub
这假定(根据您的描述和示例数据)A2包含 8948KH ,并且单元格实际上是空白的,而不是公式返回的零长度字符串。
答案 1 :(得分:0)
选择ColumnA,HOME&gt;编辑,查找&amp;选择,转到特殊...,选中空白,确定,=
,向上, Ctrl + 输入