VLookup范围在另一个工作表中动态

时间:2012-08-13 18:25:37

标签: excel excel-vba excel-formula vba

我正在尝试使用一个允许我从以前的工作表中导入范围的函数。我不确定我当前的宏允许这个。我可以手动调用上一个工作表,但不能使用我的功能。

这是我手动输入工作表名称时工作正常的函数:

=IFERROR(VLOOKUP(D3,Aug9Daily!$D$3:$F$50,3, FALSE),"")

以下是我尝试使用的功能:

=IFERROR(VLOOKUP(D3,NextSheetName()$D$3:$F$50,3, FALSE),"")

这是我用于NextSheetName宏的VBA:

Function NextSheetName(Optional WS As Worksheet = Nothing) As String
    Application.Volatile True
    Dim S As String
    Dim Q As String
    If IsObject(Application.Caller) = True Then
        Set WS = Application.Caller.Worksheet
        If WS.Index = WS.Parent.Sheets.Count Then
            With Application.Caller.Worksheet.Parent.Worksheets
                Set WS = .Item(1)
            End With
        Else 
            Set WS = WS.Next
        End If
        If InStr(1, WS.Name, " ", vbBinaryCompare) > 0 Then
            Q = "'"
        Else
            Q = vbNullString
        End If
    Else
        If WS Is Nothing Then
           Set WS = ActiveSheet
        End If
        If WS.Index = WS.Parent.Worksheets.Count Then
            With WS.Parent.Worksheets
               Set WS = .Item(1)
            End With
        Else
            Set WS = WS.Next
        End If
        Q = vbNullString
    End If
    NextSheetName = Q & WS.Name & Q
End Function

我做错了什么?有没有更好的方法从另一个工作表中动态选择范围?

2 个答案:

答案 0 :(得分:3)

尝试此操作以查看它是否适合您修复功能的输出:

NextSheetName =  Q & WS.Name & Q & "!"

然后你需要在这样的间接函数中整合输出:

=IFERROR(VLOOKUP(D3,INDIRECT(NextSheetName() & "$D$3:$F$50"),3, FALSE),"")

答案 1 :(得分:0)

我发现这个小UDF很方便:

Function sheet_offset(rng As Range, i As Integer) As Range
    Application.Volatile 'necessary since value can change even when values of parameters do not
    Set sheet_offset = rng.Worksheet.Parent.Worksheets.Item(rng.Worksheet.Index + i).Range(rng.Address)
End Function

通过i张偏移rng - 例如,i = 0表示相同的纸张,i = -1表示前一张纸,i = 1表示下一张纸。

在您的示例中,您将使用:

IFERROR(VLOOKUP(D3,sheet_offset($D$3:$F$50,1),3, FALSE),"")

会偏移范围以引用下一个工作表。

请注意,要相对于当前工作表(与您的工作表相关)进行引用,您不会指定工作表。要进行绝对引用,只需在引用中指定一个工作表(例如'Sheet1'!$ D $ 3:$ F $ 50)并成为您的原点(当i = 0时引用的工作表)

相关问题