gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:09:13 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于Excel公式如何连接字符串以供外部引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com