Excel VBA打开xlsx文件从文件夹没有写入path

我想打开Excel的xlsx文件,而不使用variables写入path。 我不知道为什么,但它不工作。 我有一个主工作簿的文件夹,另一个我想要打开的是xlsx。 我想把它命名为UnionWB。 如果有人能帮上忙,我会非常感激的。

Private Sub cmdStartMonth_Click() 'Optimize Macro Speed Application.ScreenUpdating = False Application.EnableEvents = False 'Analyze month by selecting Dim myPath As String Dim myFile As String Dim UnionWB As Workbook Dim MonthName As String MonthName = ListMonth.Value myExtension = "*.xlsx*" Set UnionWB = Workbooks.Open(ThisWorkbook.Path & myExtension) Application.ScreenUpdating = True Application.EnableEvents = True End Sub 

设置UnionWB = Workbooks.Open(ThisWorkbook.Path&myExtension)

这里有几个可能有用的例子。

第一个将要求您select正确的文件,然后打开它:

 Public Sub Test() Dim sWrkbkPath As String Dim UnionWB As Workbook sWrkbkPath = GetFile(ThisWorkbook.Path) If sWrkbkPath <> "" Then Set UnionWB = Workbooks.Open(sWrkbkPath) MsgBox UnionWB.Name End If End Sub Function GetFile(Optional startFolder As Variant = -1) As Variant Dim fle As FileDialog Dim vItem As Variant Set fle = Application.FileDialog(msoFileDialogFilePicker) With fle .Title = "Select your Union Workbook" .AllowMultiSelect = False .Filters.Add "My Union Workbook", "*.xlsx", 1 If startFolder = -1 Then .InitialFileName = Application.DefaultFilePath Else If Right(startFolder, 1) <> "\" Then .InitialFileName = startFolder & "\" Else .InitialFileName = startFolder End If End If If .Show <> -1 Then GoTo NextCode vItem = .SelectedItems(1) End With NextCode: GetFile = vItem Set fle = Nothing End Function 

第二种方法假定您只有与ThisWorkbook相同的文件夹中有一个xlsx文件,并打开它find的第一个文件:

 Public Sub OpenOnlyXLSXInFolder() Dim sWrkbkPath As String Dim UnionWB As Workbook sWrkbkPath = Dir$(ThisWorkbook.Path & "\*.xlsx") 'Only expecting a single file so no need to loop. If sWrkbkPath <> "" Then Set UnionWB = Workbooks.Open(ThisWorkbook.Path & "\" & sWrkbkPath) MsgBox UnionWB.Name End If End Sub