更改 FileDialog 左上角的 Word 图标

Changing Word Icon in Top Left of FileDialog

在 VBA 中使用 FileDialog 时有没有办法更改 Microsoft Word 图标?

原因是我使用对话框 select 文件而不是 Word 文档(或 Excel 使用 Excel VBA 时)。

请参阅下图以了解图标的视觉效果。

FileDialog 不允许您这样做。但是您可以使用 Common File Dialog instead. This involves a bit more work, and a call to the Win API.

首先您需要声明 API GetOpenFileName。

Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long

然后你需要声明OPENFILENAME结构。这允许您配置对话框。

   Private Type OPENFILENAME
     lStructSize As Long
     hwndOwner As Long
     hInstance As Long
     lpstrFilter As String
     lpstrCustomFilter As String
     nMaxCustFilter As Long
     nFilterIndex As Long
     lpstrFile As String
     nMaxFile As Long
     lpstrFileTitle As String
     nMaxFileTitle As Long
     lpstrInitialDir As String
     lpstrTitle As String
     flags As Long
     nFileOffset As Integer
     nFileExtension As Integer
     lpstrDefExt As String
     lCustData As Long
     lpfnHook As Long
     lpTemplateName As String
   End Type

使用这两个对象,您可以像这样调用公共对话框:

Private Sub Example()
    Dim OpenFile As OPENFILENAME
    Dim lReturn As Long
    Dim sFilter As String

    'Configure the dialog.
    OpenFile.lStructSize = Len(OpenFile)
    sFilter = "Batch Files (*.bat)" & Chr(0) & "*.BAT" & Chr(0)
    OpenFile.lpstrFilter = sFilter
    OpenFile.nFilterIndex = 1
    OpenFile.lpstrFile = String(257, 0)
    OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
    OpenFile.lpstrFileTitle = OpenFile.lpstrFile
    OpenFile.nMaxFileTitle = OpenFile.nMaxFile
    OpenFile.lpstrInitialDir = "C:\"
    OpenFile.lpstrTitle = "Use the Comdlg API not the OCX"
    OpenFile.flags = 0

    ' Call the dialog.
    lReturn = GetOpenFileName(OpenFile)

    ' Inspect the result.
    If lReturn = 0 Then
       MsgBox "The User pressed the Cancel Button"
    Else
       MsgBox "The user Chose " & Trim(OpenFile.lpstrFile)
    End If
End Sub

编辑: 在我原来的回答中,我没有解释如何向对话框添加图标。这是通过设置 OpenFileName 结构的 HwndOwner 属性 来完成的。对话框将拾取传递的图标 windows handle (hwnd).