[英]How to use vlookup in vba-excel?
我想做一個vlookup,找到一個值(將是1或0)之后,我要提出一個條件:如果是1,則將工作表的某些值除以100。
執行此代碼時,出現錯誤“ 1004”:無法獲取worksheetfunction類的Vlookup屬性
Sub test()
Dim inp As Workbook
Set inp = Workbooks("input_dados.xlsm")
For i = 2 To 3
For x = 2 To 112
Dim NewRange As Range
Set NewRange = inp.Sheets("Flag_divide").Range(inp.Sheets("Flag_divide").Cells(3, 2), inp.Sheets("Flag_divide").Cells(112, 3))
Dim var_macro As String
var_macro = inp.Sheets("input").Cells(x + 1, 2).Value
Dim marks As Integer
marks = Application.WorksheetFunction.VLookup(var_macro, NewRange, 2, False)
If marks = 1 Then
inp.Sheets("input").Cells(x + 1, i + 1).Value = (inp.Sheets("input").Cells(x + 1, i + 1).Value) / 100
End If
Next x
Next i
End Sub
錯誤的常見來源是找不到搜索到的值,這將引發錯誤(如果在工作表上輸入公式,也會看到該結果)。
處理此問題的首選方法是使用Application.VLookup
而不是WorksheetFunction.VLookup
。 前者可以返回錯誤,而后者則不能。 這需要將marks
更改為Variant
類型,或使用Variant
的中間變量
Dim marks as Variant
marks = Application.VLookup(var_macro, NewRange, 2, False)
If IsError(marks) Then
' Do something, or do nothing...
Else
If marks = 1 Then
inp.Sheets("input").Cells(x + 1, i + 1).Value = (inp.Sheets("input").Cells(x + 1, i + 1).Value) / 100
End If
End If
要么:
Dim marks as Integer ' or String, etc., but you're using Integer
Dim vlook as Variant
vlook = Application.VLookup(var_macro, NewRange, 2, False)
If IsError(vlook) Then
marks = Empty
Else
marks = vlook
End If
If marks = 1 Then
inp.Sheets("input").Cells(x + 1, i + 1).Value = (inp.Sheets("input").Cells(x + 1, i + 1).Value) / 100
End If
另外,您可以將函數調用加倍,但是我認為這效率低下(而且很丑陋):
Dim marks as Integer ' or String, etc., but you're using Integer
If IsError(Application.VLookup(var_macro, NewRange, 2, False)) Then
marks = Empty
Else
marks = Application.VLookup(var_macro, NewRange, 2, False)
End If
If marks = 1 Then
inp.Sheets("input").Cells(x + 1, i + 1).Value = (inp.Sheets("input").Cells(x + 1, i + 1).Value) / 100
End If
我建議采用第一種方法,原因如下:
On Error Resume Next
笨拙,難以在單個作用域中使用多個處理程序進行管理,經常被誤用等。 String
或Integer
等。 marks As String
聲明marks As String
,您正在為其分配整數值。 這可以通過隱式類型轉換來安靜地處理,但是(通常)最好避免(如果可能)。 在這種情況下,最常見的情況是您的公式找不到任何值。 但是它不能只是將Error值分配給變量,因為它不是單元格,並且對VBA的工作方式不同。 您可以通過以下方法繞過此限制:
On Error Resume Next ' Entering mode <compute it no matter what>
marks = Application.WorksheetFunction.VLookup(var_macro, NewRange, 2, False)
On Error GoTo 0 ' Returning back to a normal error handling
If IsEmpty(marks) Then marks = 0 ' Example on how to handle errors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.