Excel VBA:将variables指定为Folderspec

我有这个麻烦,希望有小问题,我似乎不知道如何解决它。

我有一个vba脚本,在将多个工作簿/工作表合并为1时效果很好。但是,该文件夹的path是一个静态path。 我想把它作为一个variables,可以由一个filedialog函数来定义。

以下是文件合并的现有代码:

Sub ProjectMerger() Dim bookList As Workbook Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object Application.ScreenUpdating = False Set mergeObj = CreateObject("Scripting.FileSystemObject") 'change folder path of excel files here Set dirObj = mergeObj.GetFolder("C:\Users\testUser\Desktop\FolderTest") Set filesObj = dirObj.Files For Each everyObj In filesObj Set bookList = Workbooks.Open(everyObj) 

这里是使用filedialog的脚本:

 Function GetFolder() As String Dim fldr As FileDialog Dim sItem As String Set fldr = Application.FileDialog(msoFileDialogFolderPicker) With fldr .Title = "Select a Folder" .AllowMultiSelect = False .InitialFileName = Application.DefaultFilePath If .Show <> -1 Then GoTo NextCode sItem = .SelectedItems(1) End With NextCode: GetFolder = sItem Set fldr = Nothing End Function 

我认为用sItem代替文件夹pathstring很容易,以使其工作,但这样做总是会导致错误。 我是否必须指定sItem作为别的东西来使用它作为path? 我不是很熟悉函数如何工作VS常规潜艇。

您只需捕获从函数返回的选定path,并处理用户取消对话框时可能为空的可能性

 Dim path As String path = GetFolder() If (path <> "") Then Set dirObj = mergeObj.GetFolder(path) .... .... Else '// user cancelled End If