首页 > 解决方案 > 在 Outlook VBA 中实现文件选择器对话框

问题描述

因此,您正在创建一个提示用户选择文件的 Outlook 宏 - 但您不能完全正确。希望这会有所帮助。

似乎有许多相关的问题,但我在这里整合所有内容并展示最终对我有用的内容。

对我来说最烦人的事情是,一旦您实施了一种解决方法,只要您不直接从 VBE 运行代码,文件对话框就会在后台打开。

标签: vbaoutlook

解决方案


从一开始,Outlook 应用程序就不支持 VBA FileDialog object。从理论上讲,Outlook 本身支持这一点,因为您可以这样做File > Save As......File > Open & Export但您不能简单地从 VBA 调用对象。

对于我的项目 - 我有一个用用户输入替换标记的子程序,但我想让人们选择打开哪个模板。我建议阅读FileDialog对象本身,因为 Microsoft 文档中有几个有用的示例。

有许多选项,但以下是我发现的 2 个主要解决方法。我更喜欢第一种方法,因为它不需要添加引用 - 这意味着可以更轻松地共享宏而不会出现编译错误。

方法 1:不需要参考(希望如此)

#If VBA7 Then
    Private Declare PtrSafe Function SetForegroundWindow Lib "user32" (ByVal win As LongPtr) As LongPtr
#Else
    Private Declare Function SetForegroundWindow Lib "user32" (ByVal win As Long) As Long
#End If
Option Explicit
Sub CreateEmailUsingSelectedTemplate()
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
'MsgBox "The top-level window handle is: " & xlApp.hWnd

Dim fd As Office.FileDialog
Set fd = xlApp.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant

SetForegroundWindow (xlApp.hWnd)
With fd
    .InitialFileName = Environ("APPDATA") & "\Microsoft\Templates\"
    .Filters.Add "All Files", "*.*", 1
    .Filters.Add "Templates", "*.oft", 2
    .FilterIndex = 2
    If .Show = -1 Then
        For Each vrtSelectedItem In .SelectedItems
            MsgBox "Selected item's path: " & vrtSelectedItem
            'FindAndReplaceTokens CStr(vrtSelectedItem)
        Next vrtSelectedItem
    Else 'If the user presses Cancel...
        MsgBox "Hit cancel instead of Accept"
        Exit Sub
    End If
End With

End Sub

方法二:提前绑定

'Set reference to 'Microsoft Excel XX Object Library' in
'Tools > References
#If VBA7 Then
    Private Declare PtrSafe Function FindWindowA Lib "user32" (ByVal class As String, ByVal caption As String) As LongPtr
    Private Declare PtrSafe Function SetForegroundWindow Lib "user32" (ByVal win As LongPtr) As LongPtr
#Else
    Private Declare Function FindWindowA Lib "user32" (ByVal class As String, ByVal caption As String) As Long
    Private Declare Function SetForegroundWindow Lib "user32" (ByVal win As Long) As Long
#End If
Option Explicit
Sub ShowDialogBox()
Dim fd As Office.FileDialog
Dim xlApp As Excel.Application
Dim hxl As LongPtr
Dim vrtSelectedItem As Variant

Set xlApp = New Excel.Application
Set fd = xlApp.FileDialog(msoFileDialogFilePicker)
hxl = FindWindowA("XLMAIN", "EXCEL")
If Not IsNull(hxl) Then
    SetForegroundWindow (hxl)
End If
If fd.Show = -1 Then
    For Each vrtSelectedItem In fd.SelectedItems
        MsgBox "Selected item's path: " & vrtSelectedItem
        'Put your code here
    Next vrtSelectedItem
Else
    MsgBox "User hit cancel"
    Exit Sub
    'Do something different here
End If
End Sub

推荐阅读