2009年11月10日 星期二

問題: 如何不開啟*.xls而直接讀取其資料?

問題: 如何不開啟*.xls而直接讀取其資料?

可用ExecuteExcel4Macro函數!
以下VBA可直接讀入[A1:E16]所有的資料到目前的工作表.

Sub GetExcelCell()
Dim arg As String
fl = Application.GetOpenFilename("*.xls (*.xls), *.xls", MultiSelect:=False)
If fl = False Then End
p = Left(fl, InStrRev(fl, "\"))
f = Right(fl, Len(fl) - InStrRev(fl, "\"))
s = "Sheet1" '請自行修改sheet名稱!
For r = 1 To 16
For c = 1 To 5
a = Cells(r, c).Address
Cells(r, c) = GetValue(p, f, s, a)
Next c
Next r
End Sub

Private Function GetValue(path, file, sheet, ref)
Dim arg As String
arg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
GetValue = ExecuteExcel4Macro(arg)
End Function

沒有留言: