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

时间:2013-04-12 18:28:04

标签: excel vba excel-vba

我想知道是否有人知道如何使用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时,我得到一个类型mismatch错误。如果我摆脱了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

1 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

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