Excel 错误的文件名或编号vba

Excel 错误的文件名或编号vba,excel,vba,Excel,Vba,我的代码不断得到一个错误的文件名或编号错误,我无法找出问题是什么,任何帮助将不胜感激!我试图将基于用户选择的文件路径存储为一个变量,稍后我可以在vlookup中引用该变量。下面是我的代码,我不知道出了什么问题,但我在另一个宏中使用了粘贴的代码,编译得很好 sub edits dim xpath and xfile as string xPath = NewPath 'Newpath function executes xfile = Dir$(xPath & "*.xlsm*", vbN

我的代码不断得到一个错误的文件名或编号错误,我无法找出问题是什么,任何帮助将不胜感激!我试图将基于用户选择的文件路径存储为一个变量,稍后我可以在vlookup中引用该变量。下面是我的代码,我不知道出了什么问题,但我在另一个宏中使用了粘贴的代码,编译得很好

sub edits
dim xpath and xfile as string
xPath = NewPath 'Newpath function executes
xfile = Dir$(xPath & "*.xlsm*", vbNormal) 'error here 
Set SourceBook = Workbooks.Open(xPath & xfile)
End Sub

Function NewPath() As String
    With Application.FileDialog(msoFileDialogOpen)
        .ButtonName = "Choose a file"
        .Title = "Previous File"
        .AllowMultiSelect = False
        If .Show Then xPath = .SelectedItems(1) & "\"
    End With
End Function
下面是我编译过的代码,它让用户选择一个文件夹而不是一个文件

sub something
dim xpath and xfile as string
xPath = NewPath
If Not strPath = vbNullString Then
xfile = Dir$(xPath & "*.xlsm", vbNormal)
Do While Not xfile = vbNullString
    'some code
    Set SourceBook = Workbooks.Open(xPath & xfile)
    SourceBook.Close False
    xfile = Dir$()
    Loop
End If
End Sub

Function NewPath() As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .ButtonName = "Choose a folder"
        .Title = "Folder Picker"
        .AllowMultiSelect = False
        If .Show Then NewPath = .SelectedItems(1) & "\"
    End With
 End Function

您在哪里得到错误?@Marcucciboy2,在这一行:xfile=Dir$(xPath&“.xlsm”,vbNormal),因此您在函数中有If.Show Then NewPath=.SelectedItems(1)和“\”,然后在子例程中将xPath重新定义为NewPath,然后在xfile中使用它。。。那么你没有得到正确的命名吗?根据XFile,这就像%userprofile%\cat.xlsm\.xlsm一样,
msoFileDialogOpen
File对话框返回文件的完整路径-因此将扩展名
.xlsm
添加到其结果中是不正确的。我认为这是过于复杂了-请参阅。不需要
Dir