ExecuteExcel4Macro从封闭的工作簿中获取值

好的,我发现这一点代码,并认为它可能是很好的使用,如果我只需要从一个封闭的工作表拉一个值。

strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3" myvalue = ExecuteExcel4Macro(strInfoCell) 

不,当我运行这个代码时,我得到了一个strinfocell的值

:strInfoCell:“'C:\ Users \ my.name \ Desktop [QOS DGL stuff.xlsx] Sheet1'!R3C3”:String

但是当我运行代码时,文件打开对话框popup,显示“QOS DGL”的桌面文件显示。

这是什么原因造成的,为什么它不是像预期的那样拉回数据呢? 我知道path和文件名是正确的,casue如果我从debugging输出复制他们,并将其粘贴到开始>>运行然后正确的工作表打开

我知道sheet1(名为:ACL),在单元格(3,3​​)中有一个值,

干杯

亚伦

这取决于你如何使用它。 正在向您显示打开的文件对话框,因为“strPath”最后没有“\”;)

试试这个代码。 有用

尝试和testing

 Option Explicit Sub Sample() Dim wbPath As String, wbName As String Dim wsName As String, cellRef As String Dim Ret As String 'wbPath = "C:\Documents and Settings\Siddharth Rout\Desktop\" wbPath = "C:\Users\my.name\Desktop\" wbName = "QOS DGL stuff.xls" wsName = "ACL" cellRef = "C3" Ret = "'" & wbPath & "[" & wbName & "]" & _ wsName & "'!" & Range(cellRef).Address(True, True, -4150) MsgBox ExecuteExcel4Macro(Ret) End Sub 

上面的代码

 strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3" myvalue = ExecuteExcel4Macro(strInfoCell) 

应该读

 strInfoCell = "'" & strPath & "[" & strFile & "]" & "Sheet1'!R3C3" myvalue = ExecuteExcel4Macro(strInfoCell) 

它缺less“&”

不需要function

干杯尼尔

类似的应用程序,但没有硬编码的path,如上面的例子。 该函数复制另一个已closures的工作簿中的值,与= INDIRECT()函数类似,但不像复杂。 这只返回值…不是一个引用,所以它不能用于需要引用的其他函数(即:VLOOKUP())。 将这段代码粘贴到一个新的VBA模块中:

 'Requires filename, sheetname as first argument and cell reference as second argument 'Usage: type in an excel cell -> =getvalue(A1,B1) 'Example of A1 -> C:\TEMP\[FILE1.XLS]SHEET1' 'Example of B1 -> B3 'This will fetch contents of cell (B3) located in (sheet1) of (c:\temp\file1.xls) 'Create a module and paste the code into the module (eg Module1, Module2) Public xlapp As Object Public Function getvalue(ByVal filename As String, ref As String) As Variant ' Retrieves a value from a closed workbook Dim arg As String Dim path As String Dim file As String filename = Trim(filename) path = Mid(filename, 1, InStrRev(filename, "\")) file = Mid(filename, InStr(1, filename, "[") + 1, InStr(1, filename, "]") - InStr(1, filename, "[") - 1) If Dir(path & file) = "" Then getvalue = "File Not Found" Exit Function End If If xlapp Is Nothing Then 'Object must be created only once and not at each function call Set xlapp = CreateObject("Excel.application") End If ' Create the argument arg = "'" & filename & "'!" & Range(ref).Range("A1").Address(, , xlR1C1) 'Execute an XLM macro getvalue = xlapp.ExecuteExcel4Macro(arg) End Function 
 Data = "'" & GetDirectory & "[" & GetFileName & "]" & Sheet & "'!" & Range(Address).Range("A1").Address(, , xlR1C1) Address = "$C$3" GetDirectory = "C:\Users\my.name\Desktop\" GetFileName = "QOS DGL stuff.xlsx" Sheet = "ACL"