我有一個代碼,用於將數據從一張紙複製到另一張使用if和vlookup功能但不工作Excel vba運行時錯誤438(如果Cl.Value像str和Rng2.Cl.Value <>「」Then)
Sub CopyRows()
Dim Rng As Range
Dim Cl As Range
Dim str As String
Dim RowUpdCrnt As Long
Set UsedRange = Sheets("Jan").Range("b5:Am81")
Set Rng = Sheets("Jan").UsedRange 'the range to search ie the used range
Set Rng2 = Sheets("Feb").Range("I5:AK5")
str = "WRK." 'string to look for
Sheets("Feb").Range("B5:B81").Value = ""
RowUpdCrnt = 5
' In my test data, the "WRK."s are in column AN. This For-Each only selects column AN.
' I assume all my "WRK."s are in a single column. Replace "B" by the appropriate
' column letter for your data.
With Sheets("Jan")
' loop until last row with data in Column AN (and not the entire column) to save time
For Each Cl In .Range("AN1:AN" & .Cells(.Rows.Count, "AN").End(xlUp).Row)
If Cl.Value Like str And Rng2.Cl.Value <> "" Then
'if the cell contains the correct value copy it to next empty row on sheet 2 & delete the row
If Not IsError(Application.Vlookup(.Range("B" & Cl.Row).Value, Sheets("Master").Range("H7:H200"), 1, 0)) Then ' <-- verify the VLookup was successful
Sheets("Feb").Range("B" & RowUpdCrnt).Value = Application.Vlookup(.Range("B" & Cl.Row).Value, Sheets("Master").Range("H7:H200"), 1, 0)
RowUpdCrnt = RowUpdCrnt + 1
End If
End If
Next Cl
End With
Application.CutCopyMode = False
End Sub
這裏不工作:'Rng2.Cl.Value'。 'Cl'是表單('Jan')中的一個範圍(單元格)。您不能像這樣在不同的工作表上訪問該範圍變量。我認爲你想在那裏訪問同一個單元格地址?嘗試'如果Cl.Value像str和Rng2.Range(Cl.Address).Value <>「」Then',而不是。 – LocEngineer
'表格(「Foobar」)'隱式指向活動工作簿。局部變量'UsedRange'和'Rng2'沒有聲明,'Rng'和'UsedRange'被分配但從未被引用。考慮在模塊頂部指定Option Explicit。您可能會發現我的[Rubberduck](http://www.rubberduckvba.com/)加載項也可用於識別其他問題 - 包括可能導致運行時錯誤438的情況。例如,如果我聲明'Rng2作爲範圍'我得到[此檢查結果](https://i.stack.imgur.com/6iCyj.png)(v2.0.12,即將發佈),這正是你在這裏遇到的問題。 –
另一件事:使用''Like''而不是通配符就像比較'Equals'一樣工作。更好的是(猜測這裏的通配符屬於哪裏):'str =「WRK。*」' – LocEngineer