繁体   English   中英

如何在vba-excel中使用vlookup?

[英]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笨拙,难以在单个作用域中使用多个处理程序进行管理,经常被误用等。
  • Vlookup公式将返回单元格中的所有内容。 这可能并不总是可以转换为StringInteger等。
  • 此外,在将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM