在VBA中使用FileDialog时,有没有办法更改Microsoft Word图标?
原因是我使用Dialog选择Word文档以外的文件(或使用Excel VBA时的Excel)。
有关图标的可视化,请参见下图。
答案 0 :(得分:3)
FileDialog不允许您这样做。但是,您可以使用Common File Dialog代替。这涉及更多工作,并调用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)的图标。