我正在使用上一个问题中帮助过的代码:(VBA Excel find and replace WITHOUT replacing items already replaced)
我有以下用于替换列中项目的代码: Sub Replace_Once() Application.ScreenUpdating = False
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("A1:A" & LastRow).Interior.ColorIndex = xlNone
For Each Cel In Range("B1:B" & LastRow)
For Each C In Range("A1:A" & LastRow)
If C.Value = Cel.Value And C.Interior.Color <> RGB(200, 200, 200) Then
C.Interior.Color = RGB(200, 200, 200)
C.Value = Cel.Offset(0, 1).Value
End If
Next
Next
哪个适用于小文件,但是当A列的长度接近3800且B和C大约有280个Excel崩溃时,我收到以下错误:
Run-time error '-2147417848 (800810108)':
Method 'Color' of object "Interior' failed
为什么会发生这种情况的任何想法?
编辑:只是澄清错误似乎发生在行
If C.Value = Cel.Value And C.Interior.Color = RGB(200, 200, 200) Then
答案 0 :(得分:2)
我对您的代码进行了一些优化。
201924100
次( 14210 Col A Rows X 14210 Col B Rows )。您不必这样做,因为B236
以后是空的。现在循环只运行3339350
次。 ( 14210 Col A Rows X 235 Col B Rows )1 Min 53 Seconds
中完成。请参阅帖子末尾的Output in Immediate window
。试试这个。这对我有用。在Excel 2013中进行了测试。
Sub Replace()
Dim ws As Worksheet
Dim A_LRow As Long, B_LRow As Long
Dim i As Long, j As Long
Application.ScreenUpdating = False
Debug.Print "process started at " & Now
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Get Col A Last Row
A_LRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Get Col B Last Row
B_LRow = .Range("B" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & A_LRow).Interior.ColorIndex = xlNone
For i = 2 To B_LRow
For j = 2 To A_LRow
If .Range("A" & j).Value = .Range("B" & i).Value And _
.Range("A" & j).Interior.Color <> RGB(200, 200, 200) Then
.Range("A" & j).Interior.Color = RGB(200, 200, 200)
.Range("A" & j).Value = .Range("B" & i).Offset(0, 1).Value
DoEvents
End If
Next j
Next i
End With
Application.ScreenUpdating = True
Debug.Print "process ended at " & Now
End Sub
立即窗口中的输出
process started at 10/18/2013 6:29:55 AM
process ended at 10/18/2013 6:31:48 AM