我正在嘗試編寫一個宏,將數據從多個外部工作簿複製到一個工作簿以特定的順序。我不打算讓每個工作簿是打開我的宏來工作,因爲這將是開放的電子表格的離譜的數字,所以我做了谷歌搜索和整個這個漂亮的功能來了,getValue函數: http://spreadsheetpage.com/index.php/tip/a_vba_function_to_get_a_value_from_a_closed_file/如何在Excel VBA中使用GetValue函數解決運行時錯誤?
爲了讓自己適應剩下的代碼,我製作了一段代碼,該代碼只需從外部工作簿的單元格中獲取單個數據,然後將其放入工作簿和工作表的單個單元格中即可目前在。在當前的工作表中,我將我想要訪問的工作簿的文件路徑粘貼到B列中,並將A列中的文件名添加到文件中,因爲有很多,我希望能夠在單個碼。下面是該代碼:
Sub Gather_Data()
Dim p As String
Dim f As String
Dim s As String
Dim a As String
p = Range("B7").Value
f = Range("A7").Value
s = Sheet5
a = D7
Cells(10, 10).Value = GetValue(p, f, s, a).Value
End Sub
Private 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
我看不出有什麼毛病的代碼,但每當我嘗試運行它,我得到的是指出,「方法‘範圍’對象的‘_Global’運行時錯誤失敗」。我真的不知道這意味着什麼,並運行調試器突出顯示
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
區域,我甚至沒有寫。如果任何人有使用此功能的經驗或知道如何解決此錯誤,您的輸入將不勝感激。提前致謝!
謝謝!我應該能夠自己嗅出這些......哎呀。 –