2013-08-29 89 views
0
Sub compare2sheetsex() 'and highlight the diffrence 
    Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet 
    Set wb1 = Workbooks(InputBox("enter b1")) 
    Set wb2 = Workbooks(InputBox("enter b2")) 
    Set sh1 = wb1.Sheets(InputBox("enter s1")) 
    Set sh2 = wb2.Sheets(InputBox("enter s2")) 
    rcount = sh1.UsedRange.Rows.Count 
    ccount = sh1.UsedRange.Columns.Count 
    Dim r As Long, c As Integer 
    For r = 1 To rcount 
     For c = 1 To ccount 
      If sh1.Cells(r, c) <> sh2.Cells(r, c) Then 
       sh2.Cells(r, c).Interior.ColorIndex = 6 
      End If 
     Next c 
    Next r 
    Set sh1 = Nothing 
    Set sh2 = Nothing 
End Sub 

問:我試圖比較兩張不同的工作簿,但我無法執行上面的代碼。如何比較不同工作簿中的兩張紙並突出顯示第二張紙上的差異?

一些未聲明的變量
+1

當您嘗試執行上述代碼時會發生什麼?你有錯誤嗎?或者只是意外的結果? –

+0

我無法執行,是的,我收到一條錯誤消息。 – Sevak

回答

0

除了(使用顯式的選項將防止這一點,並在變量名的拼寫錯誤),你的代碼工作正常,我有一些小的修改:

Option Explicit 
Sub compare2sheetsex() 'and highlight the diffrence 
    Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet 
    Dim rCount As Long, cCount As Long 
    Set wb1 = Workbooks(InputBox("enter b1")) 
    Set wb2 = Workbooks(InputBox("enter b2")) 
    Set sh1 = wb1.Sheets(InputBox("enter s1")) 
    Set sh2 = wb2.Sheets(InputBox("enter s2")) 
    rCount = sh1.UsedRange.Rows.Count 
    cCount = sh1.UsedRange.Columns.Count 
    Dim r As Long, c As Integer 
    For r = 1 To rCount 
     For c = 1 To cCount 
      If sh1.Cells(r, c) <> sh2.Cells(r, c) Then 
       sh2.Cells(r, c).Interior.ColorIndex = 6 
      End If 
     Next c 
    Next r 
    Set sh1 = Nothing 
    Set sh2 = Nothing 
End Sub 

截圖:

enter image description here

我注意到的唯一的事情是這兩個工作簿必須開放此代碼才能工作。如果你正在輸入文件名&路徑,你需要使用Workbooks.Open方法與你的輸入框,例如:

Set wb1 = Workbooks.Open(InputBox("enter b1")) 
Set wb2 = Workbooks.Open(InputBox("enter b2")) 

否則,你沒有任何錯誤處理與inputboxes所以它可能是如果您收到Subscript out of Range錯誤,您沒有正確地將輸入框輸入到工作簿或工作表名稱。

+0

您可以發送代碼嗎? – Sevak

+0

你還需要什麼代碼? –

+0

對不起,我無法完美地執行上面的代碼。我收到「訂閱超出範圍」錯誤 – Sevak

相關問題