2013-10-20 21 views
2

我試圖寫一個VBA函數,這樣我可以訪問已關閉的Excel工作簿的單元格的值。我在網上找到一個可以編寫一個宏程序是這樣的:如何將這個基於宏的功能變成真正的VBA功能?

Public Sub TestGetValue() 

    p = "C:\Users\Jake\Desktop" 
    f = "TestSample.xlsx" 
    s = "Sheet1" 
    a = "B10" 

    Call GetValue(p, f, s, a) 
    x = GetValue(p, f, s, a) 
    MsgBox x 

End Sub 

Public Function GetValue(path, file, sheet, ref) 
' Retrieves a value from a closed workbook 
    Dim arg As String 
' Make sure the file exists 
    If Right(path, 1) <> "\" Then path = path & "\" 
    If Dir(path & file) = "" Then 
     GetValue = "File Not Found" 
     Exit Function 
    End If 
' Create the argument 
    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ 
    range(ref).range("A1").Address(, , xlR1C1) 
' Execute an XLM macro 
    GetValue = ExecuteExcel4Macro(arg) 
End Function 

我可以作爲一個宏運行TestGetValue(),但是當我嘗試直接使用的GetValue(...)作爲一個自定義VBA函數Excel單元格不起作用。看起來該行

GetValue = ExecuteExcel4Macro(arg) 

無法執行。

有誰知道怎麼去解決呢?我使用Excel 2010中

+1

見[**這**](http://vba4all.wordpress.com/2013/10/11/various-ways-to-pull-data-out-of-a-closed-or-opened-使用-Excel的式工作簿和 - VBA /) – 2013-10-20 20:09:24

+0

也[**這**](http://stackoverflow.com/questions/7401967/copy-data-from-another-workbook-through-vba/19317717 #19317717)* SO回答* – 2013-10-21 07:17:48

+0

感謝,但仍.. 我知道怎麼寫,可以打開工作簿和更新數據宏,但我不知道怎麼寫了VBA功能,我可以從Excel中調用細胞。 例如,如果寫這樣的功能: 'code' 功能OpenWorkbookToPullData(路徑,小區) 昏暗openWb作爲工作簿 集openWb = Workbooks.Open(路徑) 昏暗openWs作爲工作表 集openWs = openWb.Sheets( 「工作表Sheet1」) OpenWorkbookToPullData = openWs.Range(細胞) openWb.Close(假) 端功能 'code' 不能調用從Excel單元格這個功能,雖然可以撥打它來自宏觀。 – user780069

回答

0

據我看到的,功能ExecuteExcel4Macro沒有定義。但可能有更簡單的方法。 嘗試打開包含desierd值的工作簿。例如。

tempWb as workbook 
dim testValue 

set tempWb = application.workbooks.open(path) 
testValue = tempWb.sheets(1).cells(1,1) 

路徑可以像你的例子那樣傳遞。