如何在单独的电子表格中的任意位置搜索值并返回偏移值?

时间:2018-08-02 14:47:16

标签: excel excel-vba

我有一个包含多个电子表格的工作簿,需要从另一个电子表格中查找值。主要问题是该值可以在电子表格中范围(A1:DD1000)内的任何位置。也就是说, Sheet1 中的值是“ Shelly”,在 Sheet2 中找到“ Shelly”,然后返回被+2行和+1列偏移的值。

我找到了可以满足我需要的公式,但是它很慢并且会消耗大量计算机资源。如何将此Excel公式转换为VBA? (我是VBA的新手)

=IFERROR(INDIRECT(ADDRESS(SUMPRODUCT(('Sheet2'!$A$1:$CZ$400='Sheet1'!C2)*ROW('Sheet2'!$A$1:$CZ$400))+2,(SUMPRODUCT(('Sheet2'!$A$1:$CZ$400='Sheet1'!C2)*COLUMN('Sheet2'!$A$1:$CZ$1)))+1,,,("Sheet2"))),"")

1 个答案:

答案 0 :(得分:0)

类似的事情应该对您有用。将其放在标准模块中(在Excel VBA编辑器中,转到“插入”->“模块”,然后将提供的代码复制粘贴到新模块中)。注释了代码以帮助解释其作用及其原因。

Option Explicit 'Always use Option Explicit to avoid typos

'Declare your function name and its arguments
Public Function CUSTOMLOOKUP(ByVal arg_vFind As Variant, _
                             ByVal arg_rSearch As Range, _
                             ByVal arg_lColOffset As Long, _
                             Optional ByVal arg_lRowOffset As Long = 0, _
                             Optional ByVal arg_bExactMatch As Boolean = True) _
  As Variant

    'Declare variables
    Dim rFound As Range
    Dim rOutput As Range

    'Use Range.Find method to search the provided arg_rSearch range for the arg_vFind value
    Set rFound = arg_rSearch.Find(arg_vFind, , xlValues, arg_bExactMatch)
    If rFound Is Nothing Then
        'No match found, return #VALUE! error
        CUSTOMLOOKUP = CVErr(xlErrValue)
    Else
        'Match found, check if the Column and Row offsets will result in a legal cell
        On Error Resume Next    'Use this to suppress an error if this test results in an illegal cell reference
        Set rOutput = rFound.Offset(arg_lRowOffset, arg_lColOffset)
        On Error GoTo 0         'ALWAYS use this to clear the On Error Resume Next condition immediately after the test
        If rOutput Is Nothing Then
            'Offsets result in illegal cell reference, return #REF! error
            CUSTOMLOOKUP = CVErr(xlErrRef)
        Else
            'Legal cell reference, return its value as the function output
            CUSTOMLOOKUP = rOutput.Value
        End If
    End If

End Function

现在您有了自己的VBA函数(通常称为UDF(用户定义函数)),可以通过将以下公式放在您的单元格中来调用它:=CUSTOMLOOKUP('Sheet1'!C2,'Sheet2'!$A$1:$DD$1000,1,2)