2013-10-17 52 views
2

我使用,我是在這之前的問題幫助該代碼:(VBA Excel find and replace WITHOUT replacing items already replacedExcel的VBA運行時錯誤:對象「內部」的方法,「色」失敗

我有下面的代碼,我用它來取代在物品欄: 子Replace_Once() Application.ScreenUpdating =假

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

我跑用10作爲LASTROW數你的代碼,其運行沒有任何問題。把一些錯誤陷阱,以獲得完整的錯誤 – Sorceri

+0

它運行正常,10作爲LastRow的數字,但錯誤開始出現時,數字接近3800 – genuinelycurious

+0

我跑到4000,它很好。可能是工作簿的一個問題。將數據複製到記事本中,然後回到excel中。重新運行宏。如果失敗,嘗試使用GUI手動設置單元格的顏色。你有沒有陷入錯誤?示例:出錯goto captureError captureError:如果Err.Number> 0,那麼msgbox Err.Description – Sorceri

回答

1

我做了一些優化你的代碼的情況發生。

  1. 聲明的變量/
  2. 減少你的循環時間的對象。此前您的代碼正在循環201924100次(14210 Col A行X 14210 Col B行)。你不必這樣做,因爲B236以後是空的。現在循環僅運行3339350次。 (14210 Col A行X 235 Col B行
  3. 整個代碼在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 
+0

這很棒!你介意一下這個腳本中發生的一些事情嗎? (或者至少,爲什麼它比其處理的行數減少更優化?) – genuinelycurious

+0

但我已經這樣做了;)請參閱我在帖子開頭提到的3點。 –

相關問題