I am trying to use a function that will allow me to import a range from a previous worksheet. I am not sure that my current macro allows this. I can call the previous worksheet manually, but not with the function that I have.
Here is the function that works fine when I manually input the worksheet name:
=IFERROR(VLOOKUP(D3,Aug9Daily!$D$3:$F$50,3, FALSE),"")
Here is the function that I am attempting to use:
=IFERROR(VLOOKUP(D3,NextSheetName()$D$3:$F$50,3, FALSE),"")
This is the VBA that I am using for the NextSheetName macro:
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
What am I doing wrong? Is there a better way to select a range from another worksheet dynamically?
Try this to see if it works for you to fix your function's output:
NextSheetName = Q & WS.Name & Q & "!"
And then you will need to concatinate the output inside of an indirect function like this:
=IFERROR(VLOOKUP(D3,INDIRECT(NextSheetName() & "$D$3:$F$50"),3, FALSE),"")
I've found this little UDF to be handy:
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
which offsets rng by i sheets - eg, i=0 means the same sheet, i=-1 means the previous sheet, and i=1 means the next sheet.
In your example, you'd use:
IFERROR(VLOOKUP(D3,sheet_offset($D$3:$F$50,1),3, FALSE),"")
which would offset the range to reference the next worksheet.
Note that to make references relative to the current sheet (like yours) you would not specify the worksheet. To make absolute references, just specify a worksheet in the reference (eg 'Sheet1'!$D$3:$F$50) and that becomes your origin (the sheet referenced when i=0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.