有人可以幫助使用此代碼嗎?嵌套的If語句將行剪切和粘貼到不同的工作表
我在比較兩個工作簿。我已經構建了一個For循環來檢查工作簿1中的唯一ID是否與工作簿2中的ID匹配。 如果它們匹配,我將返回的行#賦給變量lrow。然後我需要檢查C列中的返回行的值。 根據lrow中的值,C列需要剪切工作簿1,工作表1中的行並粘貼到工作簿1中的不同工作表。我也 需要刪除被切割的行,所以我沒有空白行時完成。
我收到嵌套Else If語句的語法錯誤。它們都以紅色突出顯示。我還在 這些行上寫上「必須是行中的第一條語句」的編譯錯誤。
你能讓我知道我在嵌套if缺少什麼,並驗證我的剪切和粘貼操作是否有效。
感謝您的協助。
Option Explicit
Sub Complete()
Dim Lastrow, Newrow As Long
Dim i, lrow As Long
Dim wb1, wb2 As Workbook
Dim ws1, ws2 As Worksheet
' Turn off notifications
Application.ScreenUpdating = False
Workbooks.OpenText Filename:="C:\workbook2.xlsx"
Set wb1 = ThisWorkbook
Set wb2 = Workbooks("workbook2.xlsx")
Set ws1 = wb1.Worksheets("Sheet1")
Set ws2 = wb2.Worksheets("Sheet1")
With wb1.Worksheets(ws1)
Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 2 To Lastrow
If Not IsError(Application.Match(.Cells(i, "G").Value, ws2.Columns("A"), 0)) Then
lrow = Application.Match(.Cells(i, "G").Value, ws2.Columns("A"), 0)
If ws2.Cells(lrow,"C") = 18 Then
Newrow = wb1.Worksheets("Sheet3").Range("A1").End(xlDown).Row + 1
ws1.Cells(i,"G").EntireRow.Cut wb1.Worksheets("Sheet3").Cells(newrow,"A")
ws1.Cells(i,"G").EntireRow.Delete
ElseIf ws2.Cells(lrow,"C") = 23 Then
Newrow = wb1.Worksheets("Sheet4").Range("A1").End(xlDown).Row + 1
ws1.Cells(i,"G").EntireRow.Cut wb1.Worksheets("Sheet4").Cells(newrow,"A")
ws1.Cells(i,"G").EntireRow.Delete
ElseIf ws2.Cells(lrow,"C") = 24 Then
Newrow = wb1.Worksheets("Sheet4").Range("A1").End(xlDown).Row + 1
ws1.Cells(i,"G").EntireRow.Cut wb1.Worksheets("Sheet4").Cells(newrow,"A")
ws1.Cells(i,"G").EntireRow.Delete
ElseIf ws2.Cells(lrow,"C") = 36 Then
Newrow = wb1.Worksheets("Sheet5").Range("A1").End(xlDown).Row + 1
ws1.Cells(i,"G").EntireRow.Cut wb1.Worksheets("Sheet5").Cells(newrow,"A")
ws1.Cells(i,"G").EntireRow.Delete
End If
End If
Next i
End With
Workbooks("workbook2.xlsx").Close savechanges:=False
' Turn on notifications
Application.ScreenUpdating = True
' Message Box showing that process is complete.
MsgBox "Done!"
End Sub
改變一切「否則如果「到」埃爾斯eIf「 –
@paulbica,我已經做出了您所建議的更改。但是現在我在這一行上得到了Type Mismatch錯誤:如果Application.Match(.Cells(i,「G」).value,ws2.Columns(「A」),0)Then – matt