Excel公式如何连接外部引用的string
假设我在从另一个工作簿中读取单元格值的单元格中具有以下公式
='c:\temp\[external book.xlsx]SheetX'!$E$4
我希望c:\temp\[external book.xlsx]SheetX
的值来自此工作表中的另一个单元格。 我将如何重写这个公式来连接这个值和"!$E$4"
假设单元格A1
包含c:\temp\[external book.xlsx]SheetX
编辑:由于下面不会在一个封闭的工作簿上工作,这里是一个笨拙的概念certificate,你怎么可以用VBA做到这一点(我想有更好的方法来做到这一点):
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
旧方法 (不适用于封闭的工作簿)
我相信这抓住了你要找的东西。 在这个例子中,单元格A1
有我的表格path:
'C:\temp\[externalworkbook.xlsx]Sheet1'!
在B1单元格中有以下公式:
=INDIRECT(A1 & "$E$4")
它将表单值与$E$4
,以生成完整path,然后通过INDIRECT
将其转换为值。 有一件事要注意:撇号是一个转义字符,所以根据您的数据,您可能需要在公式中特别考虑它:
=INDIRECT("'" & A1 & "$E$4")
如果您使用的是Excel 2007或更高版本,则可以将其封装在IFERROR
公式中,以取消猜测:
=IFERROR(INDIRECT(A1 & "$E$4"),INDIRECT("'" & A1 & "$E$4"))