2016-09-14 56 views
0

我正在使用Excel 2013宏從用戶選擇的工作簿中提取數據,而我的vba有點生疏。從「打開文件」對話框獲取工作簿參考

Application.GetOpenFilename提示用戶輸入文件位置,打開文件並返回字符串。 Workbooks.Open(string)返回工作簿 - 如果您事先知道該名稱。

我想結合這些來詢問用戶打開哪個文件並返回工作簿。

基於弗蘭克的答案在這裏(Open a workbook using FileDialog and manipulate it in Excel VBA)我已經試過這樣:

Function openDataFile() As Workbook 
' 
    Dim wb As Workbook 
    Dim filename As String 
    Dim fd As Office.FileDialog 
    Set fd = Application.FileDialog(msoFileDialogFilePicker) 
    fd.AllowMultiSelect = False 
    fd.Title = "Select the file to extract data" 
    'filename = fd.SelectedItems(1) 
    Set wb = Workbooks.Open(fd.SelectedItems(1)) 
    openDataFile = wb 

End Function 

但這翻倒在註釋行與Run-time error '5': Invalid procedure call or argument.

如何提示用戶打開一個excel文件,並將其作爲工作簿返回給它?

+0

請在我的回答中試試下面的代碼 –

回答

1

嘗試下面的代碼:

Function openDataFile() As Workbook 
' 
Dim wb   As Workbook 
Dim filename  As String 
Dim fd   As FileDialog 

Set fd = Application.FileDialog(msoFileDialogFilePicker) 
fd.AllowMultiSelect = False 
fd.Title = "Select the file to extract data" 

' Optional properties: Add filters 
fd.Filters.Clear 
fd.Filters.Add "Excel files", "*.xls*" ' show Excel file extensions only 

' means success opening the FileDialog 
If fd.Show = -1 Then 
    filename = fd.SelectedItems(1) 
End If 

' error handling if the user didn't select any file 
If filename = "" Then 
    MsgBox "No Excel file was selected !", vbExclamation, "Warning" 
    End 
End If 

Set openDataFile = Workbooks.Open(filename) 

End Function 

然後我在下面的子測試這一功能:

Sub test() 

Dim testWb As Workbook 

Set testWb = openDataFile  
Debug.Print testWb.Name 

End Sub 
+0

已售出!有趣的是,我不能做'Workbooks(「nameFromFileDialog」)。Activate'最初引發了這個問題。我期待'Workbooks(workbookReference).Activate'工作,但似乎我需要'Workbooks(workbookReference.Name).Activate'。所以,現在我不明白爲什麼我最初嘗試過的字符串不起作用,但工作簿名稱字符串會...(但我不會失去它的任何睡眠:) – mcalex

0

看起來你沒有表現出FileDialog所以也許是這樣的:

Function openDataFile() As Workbook 
' 
    Dim wb As Workbook 
    Dim filename As String 
    Dim fd As Office.FileDialog 
    Set fd = Application.FileDialog(msoFileDialogFilePicker) 
    fd.AllowMultiSelect = False 
    fd.Title = "Select the file to extract data" 
    fd.show 
    On Error Resume Next ' handling error over the select.. later in the script you could have an `if fileName = "" then exit sub` or something to that affect 
    fileName = fd.SelectedItems(1) 
    On Error GoTo 0 
    Set wb = Workbooks.Open(fileName) 
    openDataFile = wb 

End Function 
+0

我的代碼確實顯示FileDialog。我認爲使用.show的原因是看看filedialog是否返回true或false。 – mcalex