用ExecuteExcel4Macro从未打开的Excel工作簿中读取数据(转载) 从另外一个未打开的Excel文件中读取数据的函数 下面这个函数调用XLM宏从未打开的工作簿中读取数据. *注意: 该函数不能用于公式. GetValue函数,需要以下四个变量 path: 未打开的Excel文件的路径 (e.g., "d:\test") file: 文件名(e.g., "test.xls") sheet: 工作表的名称 (e.g., "Sheet1") ref: 引用的单元格 (e.g., "C4") '*********函数如下 Private Function GetValue(path, file, sheet, ref) ' 从未打开的Excel文件中检索数据 Dim arg As String ' 确保该文件存在 If Right(path, 1) <> "\" Then path = path & "\" If Dir(path & file) = "" Then GetValue = "File Not Found" Exit Function End If ' 创建变量 arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ Range(ref).Range("A1").Address(, , xlR1C1) ' 执行XLM 宏 GetValue = ExecuteExcel4Macro(arg) End Function 使用该函数: 将该语句复制到VBA的模块中,然后,在适当的语句中调用该函数. 下面的例子显示D:\test 下的文件test.xls 的Sheet1中的单元格”A1”的内容. Sub TestGetValue() p = "d:\test" f = "test.xls" s = "Sheet1" a = "A1" MsgBox GetValue(p, f, s, a) End Sub 下面还有一个例子.这个语句从一个未打开的文件中读取1200个数值(100行12列),并将结果填到当前工作表中. Sub TestGetValue2() p = "d:\test " f = "test.xls" s = "Sheet1" Application.ScreenUpdating = False For r = 1 To 100 For c = 1 To 12 a = Cells(r, c).Address Cells(r, c) = GetValue(p, f, s, a) Next c Next r Application.ScreenUpdating = True End Sub 说明: 如果工作簿处于隐藏状态,或者工作表是图表工作表,将会报错. ExecuteExcel4Macro
使用说明 |
|
来自: 默默小卒boe436 > 《待分类》