用户inputFileDialog到VBA中源文件的path

已解决由于它是由@ z32a7ul指出我正在使用错误的variables来声明FileDialog后的path。 它应该是OutPathS而不是OutPath。

什么代码:我有一个代码读取文件夹中的文件,打印活动工作簿中的名称,然后按升序排列名称。

Obs1:我有以下代码使用这些信息进行计算,但是这个部分与当前的问题无关。

目标:我正在尝试创build一个FileDialog,以便用户可以input源文件所在的文件夹。

问题:我为此创build了一个代码,但由于某些原因,它不会读取源文件,即使格式相同。

我到目前为止:如果我删除这个用户input,只是“源代码”的地址(假设我的采集工作簿在同一文件夹中),一切工作正常。 但是,我只能将这个“收集者”工作簿放在哪里。

问题:我没有得到具体的错误行。 结果是这个问题,因为它没有find源文件。 有没有人有什么想法在这里做什么?

码:

Option Explicit Public path As String Sub Counter() Dim count As Integer, i As Long, var As Integer Dim ws As Worksheet Dim w As Workbook Dim Filename As String Dim FileTypeUserForm As UserForm Dim X As String Dim varResult As Variant Dim OutPath As String, OutPathS As String, wPos As Long Set w = ThisWorkbook Application.Calculation = xlCalculationManual 'source input by user varResult = Application.GetSaveAsFilename(FileFilter:="Comma Separated Values Files" & "(*.csv), *.csv", Title:="OutPath", InitialFileName:="D:StartingPath") If varResult <> False Then OutPath = varResult w.Worksheets("FILES").Cells(1, 4) = varResult Else Exit Sub End If wPos = InStr(OutPath, "\StartingPath") OutPathS = Mid(OutPath, 1, wPos - 1) **'MY ERROR IS HERE, It has to be OutpathS: path = OutPath & "\*.*" 'this should be: path = OutPathS & "\*.*"** Filename = Dir(path) ThisWorkbook.Sheets("FILES").Range("A:A").ClearContents X = GetValue If X = "EndProcess" Then Exit Sub Set ws = ThisWorkbook.Sheets("FILES") i = 0 Do While Filename <> "" var = InStr(Filename, X) If var <> 0 Then i = i + 1 ws.Cells(i + 1, 1) = Filename Filename = Dir() Else: Filename = Dir() End If Loop Range("A2:A" & i).Sort key1:=Range("A2"), order1:=xlAscending, Header:=xlNo 'this will sort the names directly in the "FILES" sheet Application.Calculation = xlCalculationAutomatic ws.Cells(1, 2) = i MsgBox i & " : files found in folder" End Sub Function GetValue() With FileTypeUserForm .Show GetValue = .Tag End With Unload FileTypeUserForm End Function 

Obs2:有一个公共variables,因为它将在后续的macros中用于计算。

Obs3:整个文件部分只是查找源文件的path。 它不保存任何东西。

如果您只需要select一个文件夹,请考虑使用Application.FileDialog(msoFileDialogFolderPicker)

返回选定文件夹的函数可能如下所示

  Function GetFolder(initPath As String) As String Dim dialog As FileDialog Set dialog = Application.FileDialog(msoFileDialogFolderPicker) dialog.title = "Select a Folder" dialog.AllowMultiSelect = False dialog.InitialFileName = initPath If dialog.show Then GetFolder = dialog.SelectedItems(1) Else GetFolder = "" End If Set dialog = Nothing End Function