如何从封闭的工作簿中的特定单元格中读取信息,然后将其粘贴到使用Microsoft Excel中的VBA的活动工作表中的单元格中?

我想知道是否有人知道如何使用VBA从一个封闭的工作簿引用单元格。

我知道如何使用ADO和SQL引用一系列单元格,但我不知道如何为特定单元格创buildSQL查询。

在浏览互联网时,我遇到了一些使用“ExecuteExcel4Macro”的代码,但我无法find任何这个function/命令的真实文档。 实际上MSDN网站上关于这个命令的文档是垃圾和模糊的,并且坦率地说完全没有帮助。

无论如何,我离题了。 理想情况下,我想从外部工作簿调用单元格,而不必打开所述工作簿。 我试图去工作的代码如下:

Sub update_overview() Dim wbPath As String Dim wbName As String Dim wsName As String Dim cellRef As String Dim data As Variant wbPath = "C:\examplepath\" wbName = "Core (N)i.xls" wsName = "Sheet1" cellRef = "C5" 'data = GetData(wbPath, wbName, wsName, cellRef) ThisWorkbook.Activate Sheets("Overview").Select With Selection ActiveSheet.Range("C5").Clear ActiveSheet.Range("C5").Select ActiveCell = GetData(wbPath, wbName, wsName, cellRef) End With End Sub Private Function GetData(ByVal wbPath As String, _ wbName As String, wsName As String, cellRef As String) As Variant Dim arg As String GetData = "" arg = "'" & wbPath & "[" & wbName & "]" & _ wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1) GetData = ExecuteExcel4Macro(arg) End Function 

当我运行macros时,它返回的唯一东西是#REF

我也试过了:

 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 

当代码到达MsgBox时,我得到一个types不匹配错误。 如果我摆脱了msgbox命令,并尝试继续粘贴到单元格

 ThisWorkbook.Activate Sheets("Overview").Select With Selection ActiveSheet.Range("C5").Clear ActiveSheet.Range("C5").Select ActiveCell = ExecuteExcel4Macro(Ret) 

我仍然得到#REF! 错误

谁能告诉我:1)这是最好的技术使用? 2)我的代码有什么问题? 3)有没有更好的方法来引用单个单元格从外部工作簿使用ADO或DOA或我不知道的技术。

也没有人知道如何使用ExecuteExcel4Macro函数的任何广泛的文档。

请帮忙; 谢谢

仅供参考2003年的Excel

你可以尝试这样的事情:

arg = "='" & wbPath & "[" & wbName & "]" & wsName & "'!" & cellRef

 Sub Test() Dim wbName As String Dim wbPath As String Dim wsName As String Dim cellRef As String Dim calcState As Long calcState = Application.Calculation wbPath = "C:\users\david_zemens\" wbName = "a report.xlsx" wsName = "Sheet1" cellRef = Range("B2").Address Dim arg As String arg = "='" & wbPath & "[" & wbName & "]" & wsName & "'!" & cellRef 'Range(cellRef).Address(True, True, xlR1C1) Application.Calculation = xlCalculationManual Application.DisplayAlerts = False ActiveCell.Value = arg ActiveCell.Value = ActiveCell.Value 'essentially a paste/values over the formula. Application.DisplayAlerts = True Application.Calculation = calcState End Sub