Home » excel » Excel formula how to concatenate string for external reference

Excel formula how to concatenate string for external reference

Posted by: admin May 14, 2020 Leave a comment

Questions:

Say I have the following formula in a cell that reads the value of a cell from another work book

='c:\temp\[external book.xlsx]SheetX'!$E$4

and I want the value of c:\temp\[external book.xlsx]SheetX to come from another cell in this sheet. How would I rewrite this formula to concatenate this value and "!$E$4"

Lets say the cell A1 contains c:\temp\[external book.xlsx]SheetX

How to&Answers:

EDIT: As the below won’t work on a closed workbook, here is a clunky proof-of-concept of how you could do it with VBA (I imagine there are better ways of doing this):

Sub ClosedWorkbook()

Dim currSht As Worksheet
Dim targetWbk As Workbook
Dim Path As String

' Turn off updating
Application.ScreenUpdating = False

' Set a reference to the current sheet
Set currSht = ActiveWorkbook.ActiveSheet

' Get the value in the formula cell (A1 here, could be ActiveCell if in a loop, etc.)
PathSheet = currSht.Range("A1").Value

' Split out the path - this is very clunky, more of a proof (?) of concept
' This is depends on the path being as you mentioned, and the IF block is to 
' check if the apostrophe is present in the cell (since it is the escape character,
' it is usually skipped)
If Left(PathSheet, 1) = "'" Then
  Path = Replace(Mid(PathSheet, 2, InStr(PathSheet, "]") - 2), "[", "")
  Sheet = Mid(PathSheet, InStr(PathSheet, "]"))
  Sheet = Left(Sheet, Len(Sheet) - 2)
Else
  Path = Replace(Mid(PathSheet, 1, InStr(PathSheet, "]") - 1), "[", "")
  Sheet = Mid(PathSheet, InStr(PathSheet, "]") + 1)
  Sheet = Left(Sheet, Len(Sheet) - 2)
End If

' Open the target workbook
Set targetWbk = Workbooks.Open(Path)

' Grab the value from E4 and drop it in a cell (D1 here, could be ActiveCell, etc.)
MyValue = targetWbk.Sheets(Sheet).Range("E4").Value
currSht.Range("D5").Value = MyValue

' Close the target
targetWbk.Close

Application.ScreenUpdating = True
End Sub

OLD WAY (doesn’t work on closed workbooks)

I believe this captures what you’re looking for. In this example, cell A1 had my sheet path:

'C:\temp\[externalworkbook.xlsx]Sheet1'!

In cell B1 I have the formula:

=INDIRECT(A1 & "$E$4")

Which concatenates the sheet value with $E$4 in order to generate the full path, which is then turned into a value by INDIRECT. One thing to note: the apostrophe is an escape character, so depending on your data, you may have to account for it specially in your formula:

=INDIRECT("'" & A1 & "$E$4")

If you’re using Excel 2007 or above, you could wrap it in an IFERROR formula to take out the guesswork:

=IFERROR(INDIRECT(A1 & "$E$4"),INDIRECT("'" & A1 & "$E$4"))