我只是想用Vlookup做一些非常简单的事情,但是我得到了1004错误。真的,非常感谢你的帮助。提前致谢。这是我的代码:
Sub test()
Dim user As String
Dim drawn As String
Set Sheet = ActiveWorkbook.Sheets("consolidated")
For i = 2 To 2092
user = CStr(Cells(i, 1).Value)
Set Sheet = ActiveWorkbook.Sheets("sections")
drawn = CStr(Application.WorksheetFunction.VLookup(user, Sheet.Range("A2:B3865"), 2))
Set Sheet = ActiveWorkbook.Sheets("consolidated")
Cells(i, 10).Value = drawn
Next i
End Sub
答案 0 :(得分:3)
当您将VLOOKUP用作WorksheetFunction的成员时,错误将导致运行时错误。当您使用VLOOKUP作为Application的成员时,错误将导致返回值为错误,这可能会也可能不会导致运行时错误。我不知道为什么MS会这样设置它。
如果使用WorksheetFunction,则应捕获错误。如果使用Application,则应使用Variant变量并测试IsError。以下是几个例子。
Sub VlookupWF()
Dim sUser As String
Dim sDrawn As String
Dim shSec As Worksheet
Dim shCon As Worksheet
Dim i As Long
Set shSec = ActiveWorkbook.Worksheets("sections")
Set shCon = ActiveWorkbook.Worksheets("consolidated")
For i = 2 To 2092
sUser = shCon.Cells(i, 1).Value
'initialize sDrawn
sDrawn = vbNullString
'trap the error when using worksheetfunction
On Error Resume Next
sDrawn = Application.WorksheetFunction.VLookup(sUser, shSec.Range("A2:B3865"), 2, False)
On Error GoTo 0
'see if sdrawn is still the initialized value
If Len(sDrawn) = 0 Then
sDrawn = "Not Found"
End If
shCon.Cells(i, 10).Value = sDrawn
Next i
End Sub
Sub VlookupApp()
Dim sUser As String
Dim vDrawn As Variant 'this can be a String or an Error
Dim shSec As Worksheet
Dim shCon As Worksheet
Dim i As Long
Set shSec = ActiveWorkbook.Worksheets("sections")
Set shCon = ActiveWorkbook.Worksheets("consolidated")
For i = 2 To 2092
sUser = shCon.Cells(i, 1).Value
vDrawn = Application.VLookup(sUser, shSec.Range("A2:B3865"), 2, False)
'see if vDrawn is an error
If IsError(vDrawn) Then
vDrawn = "Not Found"
End If
shCon.Cells(i, 10).Value = vDrawn
Next i
End Sub