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

Excel 如何在单独的电子表格中的任意位置搜索值并返回偏移值?,excel,vba,Excel,Vba,我有一个包含多个电子表格的工作簿,需要从不同的电子表格中查找值。主要问题是该值可能位于电子表格中A1:DD1000范围内的任何位置。i、 e.Sheet1中的值为“Shelly”,在Sheet2中找到“Shelly”,并返回偏移+2行和+1列的值 我已经找到了一个公式,它可以满足我的需要,但是它非常慢,并且消耗了大量的计算机资源。如何将此excel公式转换为VBA?我对VBA很陌生 =IFERROR(INDIRECT(ADDRESS(SUMPRODUCT(('Sheet2'!$A$1:$CZ$4

我有一个包含多个电子表格的工作簿,需要从不同的电子表格中查找值。主要问题是该值可能位于电子表格中A1:DD1000范围内的任何位置。i、 e.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"))),"")

像这样的东西应该适合你。将其放入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

你不能用公式来计算。这是不实际的。明天如果你的工作表增加了,你会在公式中添加更多的名字吗?使用VBA并使用。在web上查找大量示例