有點(diǎn)興奮,今天不經(jīng)意找到以前一直在找的一個(gè)EXCEL VBA功能,就是從關(guān)閉的工作薄中取得某一工作表某一單元格數值,以前做的時(shí)候都要先打開(kāi)取數,再關(guān)閉,實(shí)在太麻煩了.
網(wǎng)上別人寫(xiě)的代碼共享如下:
Private Function GetValue(path, file, sheet, ref)
' 從關(guān)閉的工作薄返回值
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)
'執行EXCEL4宏函數
GetValue = Application.ExecuteExcel4Macro(arg)
End Function
'參數說(shuō)明
'-----------------------------------------------------------------
'path:文件路徑
'file:文件名稱(chēng)
'sheet:工作表名稱(chēng)
'ref: 單元格區域
'-----------------------------------------------------------------
Sub kk()
Range("a1").Value = GetValue("D:\", "book2.xls", "Sheet1", "b2")
End Sub
直接讀取c:\test.xls(不打開(kāi))中sheet1.a1的值另一種參考代碼 (比一樓的寫(xiě)法簡(jiǎn)單許多)
Sub TestGetValue()
str0 = "'C:\[test.xls]Sheet1'!R1C1"
MsgBox ExecuteExcel4Macro(str0)
End Sub