宏中的FilePicker在后台打开对话框

我已经开发了一个Outlook宏,可以让用户选择并打开一个excel文件。

问题是文件对话框没有在所有内容的顶部打开,而是在后台打开。这样,对于用户来说,Outlook应用程序似乎卡住了,而它只是在等待用户在所有其他窗口后面的“文件选择器”对话框中选择一个文件。

代码如下:

Dim SigFolder2 As String
Dim fd As Office.FileDialog
Dim selectedItem As Variant
Dim ExcelFileName As String
Dim FileName As String
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook


'Suggested Folder--Downloads
SigFolder2 = "C:\Users\" & Environ("username") & "\Downloads\"

'Dialog Settings

Set fd = objExcel.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
 .InitialFileName = SigFolder2
 .AllowMultiSelect = False
 .Title = "Select Signature File"
End With

'Getting the file
If fd.Show = -1 Then
    For Each selectedItem In fd.SelectedItems
        SigFolder = selectedItem
    Next
Else
Exit Sub
End If

ExcelFileName = SigFolder
FileName = Left(fso.GetFileName(ExcelFileName),InStr(fso.GetFileName(ExcelFileName),".") - 1)
Debug.Print ExcelFileName 'file Path with filename

有什么办法可以纠正这个问题?

zhangshaodan123 回答:宏中的FilePicker在后台打开对话框

此问题是由于Excel窗口对Outlook窗口一无所知而引起的。如果要将父窗口始终保持在另一个窗口的顶部,则必须将其设置为子窗口对话框。例如:

Public Declare Function SetForegroundWindow _
Lib "user32" (ByVal hwnd As Long) As Long

Public Sub Bring_to_front()
    Dim setFocus As Long

    ThisWorkbook.Worksheets("Sheet1").Activate
    setfocus = SetForegroundWindow(Application.hwnd)
End Sub

在您的情况下,它将是一个对话框窗口:

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

Dim hxl As Long

Set objExcel = New Excel.Application
Set fd = xl.FileDialog(msoFileDialogFilePicker)
hxl = FindWindowA("XLMAIN","Excel")
If (hxl <> 0) Then
    res = SetForegroundWindow(hxl)
End If
With fd
.Filters.Clear
 .InitialFileName = SigFolder2
 .AllowMultiSelect = False
 .Title = "Select Signature File"
End With
res = fd.Show
本文链接:https://www.f2er.com/3152004.html

大家都在问