Excel VBA从文件夹打开xlsx文件而不写路径

时间:2017-11-08 09:17:17

标签: excel vba excel-vba

我想打开Excel xlsx文件而不使用变量编写路径。我不知道为什么但它不起作用。我有一个主工作簿的文件夹和另一个我要打开的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)

1 个答案:

答案 0 :(得分:2)

以下是一些可能有用的示例。

第一个会要求您选择正确的文件,然后将其打开:

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文件,并打开它找到的第一个文件:

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