【问题标题】:Excel formula how to concatenate string for external referenceExcel公式如何连接字符串以供外部参考
【发布时间】:2012-10-31 12:18:23
【问题描述】:

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

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

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

假设单元格A1 包含c:\temp\[external book.xlsx]SheetX

【问题讨论】:

  • 是否可以将其写为 Excel 函数,可以从单元格中调用 A1=INDIRECT_2(A2) 的单元格公式和 A2='c:\temp[external book .xlsx]SheetX'!$E$4

标签: excel excel-formula


【解决方案1】:

编辑:由于以下内容不适用于封闭的工作簿,因此这里有一个笨拙的概念证明,说明如何使用 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"))

【讨论】:

  • @PreetSangha 是的,意思是把它放在那里。关了我看看能不能想出点什么。
  • 谢谢,但如果外部工作簿 (a) 关闭或 (b) 在不同的 Excel 实例中打开,则间接不起作用
  • @PreetSangha 可以选择 VBA 吗?另外,我会在这篇文章中添加excel 标签——有些人比我优秀得多,他们可能会有更好的想法。
  • 当然,如果这是唯一的方法,那么我很高兴
  • @PreetSangha 好的,现在将样本放在那里。绝对不会为此感到自豪-更多的是概念证明。依赖于打开/关闭目标书,因此希望它适合您的用例。如果它适合您的事业,很乐意帮助充实它/使其更具活力。
猜你喜欢
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 2016-09-20
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多