我想知道是否有人知道如何使用 VBA 从封闭的工作簿中引用单元格。
我知道如何使用 ADO 和 SQL 引用一系列单元格,但我不知道如何为特定单元格创建 SQL 查询。
在浏览互联网时,我遇到了一些使用“ExecuteExcel4Macro”的代码,但我找不到该函数/命令的任何真实文档。事实上,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
当我运行宏时,它唯一返回的是#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 时,我收到类型不匹配错误。如果我摆脱 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 函数的任何详细文档。
请帮忙; 谢谢
仅供参考,我在 excel 2003 上