2016-10-24 191 views
0

我做了一個宏有多個子。在其中一個潛艇我得到的錯誤。在此子之前,代碼運行良好,但在此活動工作表切換到工作表2時,我在指定的行中收到錯誤。我得到「運行時錯誤」424:所需的對象「錯誤

Sub Matchr() 
counter = 0 
Dim k As Integer 
Sheets("Sheet2").Select 

k = Sheet2.UsedRange.Rows.Count + 5 '<-- This line is throwing the error. 

Set S1 = Worksheets("Sheet1") 
Set S2 = Worksheets("Sheet2") 

For i = 7 To S2.UsedRange.Rows.Count 
    For J = 7 To S1.UsedRange.Rows.Count 
     If Sheet2.Cells(i, "J") = Sheet1.Cells(J, "J") Then 
      counter = 1 
     End If 
    Next J 

    If counter = 0 Then 
     Sheet2.Cells(k, "I") = Sheet2.Cells(i, "I") 
     Sheet2.Cells(k, "J") = Sheet2.Cells(i, "J") 
     Sheet2.Cells(k, "K") = Sheet2.Cells(i, "K") 
     k = k + 1 
    End If 
    counter = 0 
Next i 

Range("I45:I58").Select 
    Selection.NumberFormat = "[$-409]d-mmm-yy;@" 
    Range("J63").Select 

End Sub 

請注意,給定的代碼工作正常,當我運行它爲宏的按鈕。我在Personal XLSB文件中運行時遇到錯誤。

+1

你[不需要選擇(http://stackoverflow.com/q/10714251/11683)任何東西。這可以解決它。 – GSerg

+4

我懷疑是因爲你使用了代碼名(即'Sheet1'和'Sheet2')而不是你的變量('S1'和'S2')。你爲什麼要混合它們? – Comintern

+1

如果「突出顯示的行」是'k = Sheet2.UsedRange.Rows.Count = 5',那是因爲沒有'Sheet2'這樣的東西。你的代碼也會在稍後拋出錯誤。快速修復:將該行放在設置爲「S1」和「S2」的下方,並用「S2」替換「Sheet2」。 – PartyHatPanda

回答

3

大量清理的需要:

Sub Matchr() 

    Dim k As Integer, S1 as Worksheet, S2 as Worksheet 
    Set S1 = Worksheets("Sheet1") 
    Set S2 = Worksheets("Sheet2") 

     k = S2.UsedRange.Rows.Count + 5 

    For i = 7 To S2.UsedRange.Rows.Count 
     For J = 7 To S1.UsedRange.Rows.Count 
      If S2.Cells(i, "J") = S1.Cells(J, "J") Then 
       'Do Nothing 
      Else 
       S2.Cells(k, "I").Resize(1, 3) = S2.Cells(i, "I").Resize(1, 3) 
       k = k + 1     
      End If 
     Next J 
    Next i 

    Range("I45:I58").NumberFormat = "[$-409]d-mmm-yy;@" 'This range needs a S1. or S2. before it to define the correct Sheet! 
End Sub 
+0

@ScottCraner另外最後一個範圍需要一個表名... – Chrismas007

+0

@PranavM我剛剛做了一個你沒有看到的編輯。請使用修改後的代碼。 – Chrismas007

+0

您仍然有兩個'S2'引用,而不是一個'S1'和一個'S2'。 – Jeeped