用ExecuteExcel4Macro從未打開的Excel工作簿中讀取數(shù)據(jù)(轉(zhuǎn)載) 從另外一個(gè)未打開的Excel文件中讀取數(shù)據(jù)的函數(shù) 下面這個(gè)函數(shù)調(diào)用XLM宏從未打開的工作簿中讀取數(shù)據(jù). *注意: 該函數(shù)不能用于公式. GetValue函數(shù),需要以下四個(gè)變量 path: 未打開的Excel文件的路徑 (e.g., "d:\test") file: 文件名(e.g., "test.xls") sheet: 工作表的名稱 (e.g., "Sheet1") ref: 引用的單元格 (e.g., "C4") '*********函數(shù)如下 Private Function GetValue(path, file, sheet, ref) ' 從未打開的Excel文件中檢索數(shù)據(jù) Dim arg As String ' 確保該文件存在 If Right(path, 1) <> "\" Then path = path & "\" If Dir(path & file) = "" Then GetValue = "File Not Found" Exit Function End If ' 創(chuàng)建變量 arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ Range(ref).Range("A1").Address(, , xlR1C1) ' 執(zhí)行XLM 宏 GetValue = ExecuteExcel4Macro(arg) End Function 使用該函數(shù): 將該語句復(fù)制到VBA的模塊中,然后,在適當(dāng)?shù)恼Z句中調(diào)用該函數(shù). 下面的例子顯示D:\test 下的文件test.xls 的Sheet1中的單元格”A1”的內(nèi)容. Sub TestGetValue() p = "d:\test" f = "test.xls" s = "Sheet1" a = "A1" MsgBox GetValue(p, f, s, a) End Sub 下面還有一個(gè)例子.這個(gè)語句從一個(gè)未打開的文件中讀取1200個(gè)數(shù)值(100行12列),并將結(jié)果填到當(dāng)前工作表中. 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 說明: 如果工作簿處于隱藏狀態(tài),或者工作表是圖表工作表,將會(huì)報(bào)錯(cuò). ExecuteExcel4Macro
使用說明 |
|