簡體   English   中英

如何在VBA中使用VLookup作為范圍參數?

[英]How do I use a VLookup as range parameter in 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行之間的任何位置)。

也許是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM