2012-01-06 38 views
0

我已經編寫了一個Visual Basic程序,它連接到Access數據庫,生成一些SQL語句,然後嘗試將結果寫入Excel文件。將Excel SaveAs對話框置於Visual Basic(不是VBA)的前面

一切工作正常,除了當它調用另存爲對話框:

xlApp.Dialogs(Excel.XlBuiltInDialog.xlDialogSaveAs).Show() 

的對話框程序,這是最大的後面。因此,該程序似乎掛起,因爲它正在等待關閉對話框,但對話框無法訪問(除Alt + Tab,但這是一個醜陋的解決方法)。

任何方式讓我強制對話框到前面?我發現一個相關的線程here,但我不處理單獨的線程。那裏的OP建議BringToFront方法,但我不知道如何使用我的xlApp.Dialogs。

在此先感謝您的幫助!

回答

0

查找窗口句柄,並調用SetForegroundWindow

Public Function FindWindowByPartialTitle(ByVal _ 
    TestFlex_string As String) As Long 
    m_TestFlexString = TestFlex_string 
    m_TestFlexHwnd = 0 

    ' Enumerate windows. 
    EnumWindows AddressOf EnumCallback, 0 

    ' Return the hWnd found (if any). 
    FindWindowByPartialTitle = m_TestFlexHwnd 
End Function 

' Check a returned task to see if it's the one we want. 
Public Function EnumCallback(ByVal app_hWnd As Long, ByVal _ 
    param As Long) As Long 
Dim buf As String 
Dim title As String 
Dim Length As Long 

    ' Get the window's title. 
    Length = GetWindowTextLength(app_hWnd) 
    buf = Space$(Length) 
    Length = GetWindowText(app_hWnd, buf, Length) 
    title = Left$(buf, Length) 

    ' See if the title contains the TestFlex string. 
    If InStr(title, m_TestFlexString) <> 0 Then 
     ' This is the one we want. 
     m_TestFlexHwnd = app_hWnd 

     ' Stop searching. 
     EnumCallback = 0 
    Else 
     ' Continue searching. 
     EnumCallback = 1 
    End If 
End Function 

因此,與上述功能,你應該能夠做這樣的事情:

Dim saveAsHwnd as Long 

call saveAsHwnd = FindWindowByPartialTitle("Save") 
call SetForegroundWindo(saveAsHwnd) 

不要忘記decalre SetForegroundWindow還有:

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