Excel公式如何连接字符串以供外部引用

时间:2012-10-24 23:21:26

标签: excel excel-formula

假设我在一个单元格中有以下公式,该单元格从另一个工作簿中读取单元格的值

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

我希望c:\temp\[external book.xlsx]SheetX的值来自此工作表中的另一个单元格。如何重写此公式以连接此值和"!$E$4"

让我们说单元格A1包含c:\temp\[external book.xlsx]SheetX

1 个答案:

答案 0 :(得分:3)

编辑:由于以下内容无法在已关闭的工作簿上运行,因此以下是关于如何使用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

OLD WAY (对已关闭的工作簿无效)

我相信这可以捕捉到您正在寻找的东西。在此示例中,单元格A1具有我的工作表路径:

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

在单元格B1中,我有以下公式:

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

将工作表值与$E$4连接起来以生成完整路径,然后将其转换为INDIRECT的值。有一点需要注意:撇号是一个转义字符,因此根据您的数据,您可能需要在您的公式中特别考虑它:

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

如果您使用的是Excel 2007或更高版本,则可以将其包装在IFERROR公式中以消除猜测:

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