如何在VBA中使用VLookup作为范围参数?

时间:2019-05-09 01:35:42

标签: excel vba

我的IF语句可以正常工作,但是我需要使用VLookup作为范围,因为作为IF主题的单元格可以在不同的行中,但不能在不同的列中。

我是VBA的新手(但并不擅长),因此VLookup是本能的举动,但是如果我可以通过其他方式实现同​​样的目标,我就不会受到束缚。我一直在尝试在线查找解决方案,但似乎并未真正回答该查询。

下面是具有静态范围的原始代码。

Sub FINDTOTAL()

Dim Amount As String
Amount = "Subtotal"

thetotal = Application.WorksheetFunction.Vlookup(Amount, Sheet1.Range("G:H"), 2, False)

End Sub

Sub CalculateSubtotal()

If Range("H25") > 10000 Then
    Sheets("Billing").Select
Else
    Worksheets("Sheet1").Range("H25").Copy
    MsgBox "Subtotal has been copied and can be pasted into the quote"

End If
End Sub

VLookup有效,而IF语句有效,我只是不能让它们一起工作。我需要对IF语句的小计进行评估,无论它在列中的什么位置(可能在3至50行之间的任何地方)。

1 个答案:

答案 0 :(得分:0)

也许是这样的:

Sub FindTotal()

    Dim Total As Variant
    Total = Application.VLookup("Subtotal", Sheet1.Range("G:H"), 2, False)

    If Not IsError(Total) Then
        If IsNumeric(Total) Then
            If Total > 10000 Then
                ' Do one thing
            Else
                ' Do another thing
            End If
        End If
    End If

End Sub

如果要将总数写入其他位置的其他单元格,则无需复制,只需直接进行值转移即可。


演示Find / Offset方法:

Sub FindTotal()

    Dim rng As Range
    Set rng = Sheet1.Columns("G").Cells.Find(What:="Subtotal")

    If Not rng Is Nothing Then
        Dim totalRng As Range
        Set totalRng = rng.Offset(, 1)

        If IsNumeric(totalRng.Value) Then
            If totalRng.Value > 10000 Then
                ' Do one thing
            Else
                ' Do another thing
            End If
        End If
    End If
End Sub