无法为 getopenfilename 设置默认目录

问题描述

我正在尝试为 VBA 函数 Getopenfilename 设置认目录。我之前设法让它工作,但遗憾的是在保存之前丢失了代码我有以下代码

Sub Sample2()
    Dim myFile As Variant
    Dim i As Integer
    Dim myApp As Excel.Application
    Dim strCurDir As String
    Set myApp = New Excel.Application

    ChDrive ("H:\")
    ChDir ("H:\99 - Temp")

    'Open File to search
    myFile = myApp.GetopenFileName(MultiSelect:=True)

    If myFile <> False Then
        If IsArray(myFile) Then  '<~~ If user selects multiple file
            For i = LBound(myFile) To UBound(myFile)
                Debug.Print myFile(i)
            Next i
        Else '<~~ If user selects single file
            Debug.Print myFile
        End If
    Else
        Exit Sub
    End If

End Sub

我尝试了此代码的几种变体,但都没有成功,而且我发现的所有帖子都很旧。如果这有什么不同,它将成为 Outlook 2016 中更大代码的一部分。

谢谢

解决方法

尝试使用 Excel 对象的 FileDialog 属性...

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")

Dim myFile As Variant
With xlApp.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = True
    .ButtonName = "Select"
    .Title = "Select File"
    .InitialFileName = "H:\99 - Temp\"
    If .Show = 0 Then Exit Sub 'user cancelled
    For Each myFile In .SelectedItems
        Debug.Print myFile
    Next myFile
End With

Set xlApp = Nothing