Excel(WPS)使用VBA,不打开文件情况下提取其他工作簿数据
提取函数,返回提取到的值使用示例在不打开工作簿的情况下,VBA读取其他工作簿数据
很多方法需要打开才能提取,如果没打开会显示错误,比如inderect函数等
提取函数,返回提取到的值
path:文件路径
file:文件名
sheet:工作表名
ref:需要读取的目标单元格
Private Function GetValue(path, file, sheet, ref)' 从未打开的Excel文件中检索数据Dim arg As String' 确保该文件存在If Right(path, 1) <> "" Then path = path & ""If Dir(path & file) = "" ThenGetValue = "File Not Found"Exit FunctionEnd If' 创建变量arg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)' 执行XLM 宏GetValue = ExecuteExcel4Macro(arg)End Function
使用示例
比如需要读取的文件为D:\Test\data.xlsx,
工作表名为Sheet1,
读取D9单元格的内容:
读取后存放到本表的C7单元格中
'注意不要漏掉最后的 \path = "D:\Test\file = "data.xlsx"sheet = "Sheet1"address = "D9"Cells(7, "C") = GetValue(path, file, sheet, address)