簡體   English   中英

在vba中是否有一個等效於vlookup的數組?

[英]Is there an array equivalent to vlookup in vba?

我的大量VBA代碼使用worksheetfunction.vlookup查找所需的值。 但是,范圍可以超過25,000個單元,因此這需要永遠。 數組有等效功能嗎?

我已經看過很多SO答案,這些答案似乎解決了在精確匹配字符串的情況下返回true / false的問題。 我需要字符串的位置。

這個怎么樣 ...

Function MyVLook(Arg As Range, Target As Range, ColIdx As Integer) As Range
Dim Idx As Integer

    If Arg = "" Then
        Set MyVLook = [ParamNothing]
    Else
        For Idx = 1 To Target.Rows.Count

            If Target(Idx, 1) = Arg Then
                If ColIdx < 0 Then
                    Set MyVLook = Target(Idx, 1).Offset(0, ColIdx)
                Else
                    Set MyVLook = Target(Idx, ColIdx)
                End If
                Exit For
            End If

        Next Idx
    End If
End Function

[ParamNothing]是工作表中的單個單元格區域,其中包含一些特定於應用程序的文本; 否則,它的工作原理幾乎與普通的VLOOKUP相似...但是,您可以指定負的列偏移 (在常規VLOOKUP中我經常會錯過的東西),並且我沒有為范圍搜索構建標記。

如果您只尋找第一次出現的情況,請嘗試以下操作:

Public Sub FindInRange()

    Dim sValueToFind As String
    Dim rRangeToSearch As Range
    Dim rFoundRange As Range

    sValueToFind = "The value I'm searching for"

    With ThisWorkbook.Worksheets("Sheet1")
        Set rRangeToSearch = .Range("A1:A1193")

        Set rFoundRange = rRangeToSearch.Find( _
            What:=sValueToFind, _
            After:=rRangeToSearch.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchDirection:=xlNext, _
            MatchCase:=False)

        If Not rFoundRange Is Nothing Then
            MsgBox sValueToFind & " found in cell " & rFoundRange.Address & _
             " and the value two cells to the right is " & rFoundRange.Offset(, 2), vbInformation + vbOKOnly
        Else
            MsgBox sValueToFind & " not found.", vbInformation + vbOKOnly
        End If

    End With

End Sub

由於LookAt:= xlWhole,這將找到完全匹配,而由於MatchCase:= False,這將不匹配大小寫。 如果要查找最后一次出現,請使用SearchDirection:= xlPrevious。

這類似於在工作表上使用Ctrl +F。 有關VBA FIND的更多信息,請參見: https : //msdn.microsoft.com/zh-cn/library/office/ff839746.aspx

暫無
暫無

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

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