2013-02-15 52 views
2

我遇到了問題。麻煩瀏覽和選擇文件IE/VBA

我有一個頁面,我需要上傳文件。當我點擊'瀏覽器'時,'選擇要上傳的文件'窗口打開,我需要選擇(雙擊)那裏的一個TXT文件。

我嘗試使用Set fd = Application.FileDialog(msoFileDialogFilePicker),但無法識別此對象。

任何幫助將不勝感激!

Sub Main 
    ' Get the browser object belonging to the active/topmost IE tab 
    Dim objIe 
    Dim activeDocument 
    Dim Button 
    Set activeDocument = Nothing 


    ' Try and get the window object of the active IE tab 
    Set objIe = GetActiveBrowserObj 'this is a function previously defined that allows me to work on the active browser window 
     If objIe Is Nothing Then 
      MsgBox "Could not get active IE document object」 
      Exit Sub 
     End If 

    ' Assign the document object to the activeDocument variable 
    Set activeDocument = objIe.Document 
     If activeDocument Is Nothing Then 
      MsgBox "Could not get active IE document object" 
      Exit Sub 
     End If 
    'Click the browse button to upload the first TXT file 
    Set Button = objIe.Document.getElementById("txtfile1") 
     Button.Click 

    chooseFile() 

End Sub 

Private Sub chooseFile() 

    Dim fd 
    Dim strTxt As String 

    Start: 
    'Set fd = Application.FileDialog(msoFileDialogFilePicker) 
    With fd 
     .Title = "Choose File to Upload" 'Change the title to suit 
     .Filters.Add "txt files", "*.txt", 1 'Change the filters to suit, or omit for none 
     .AllowMultiSelect = False 
     If .Show = -1 Then 
      'The user made a selection. The variable strWorkBook will contain the path\name of the file 
      strTxt = .SelectedItems(1) 
     Else 
      response = MsgBox("You have not selected a txt file") 
      If response = vbRetry Then 
       GoTo Start 
      Else 
       Exit Sub 
      End If 
     End If 
    End With 
    Set fd = Nothing 
End Sub 

回答

2

你將不得不使用API​​來與窗口交互通過查找其名稱的窗口「選擇要上傳的文件

下面是一個例子

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _ 
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long 

Sub Sample() 
    Dim Ret 

    Ret = FindWindow(vbNullString, "Choose File To Upload") 

    If Ret <> 0 Then 
     MsgBox "File upload window Found" 
    Else 
     MsgBox "File upload window Not Found" 
    End If 
End Sub 

一旦你已經鎖定到相關窗口,那麼你必須找到TextboxHandle,然後在那裏粘貼你的文件名和完整路徑。完成之後,您會找到Open按鈕的句柄,最後單擊它。

我已經詳細報道了here。雖然我在鏈接中發佈的示例中,我使用Save As保存文件,但您必須使用相同的方法來查找句柄並上載文件。

HTH

+0

感謝您的回答。我試過你的代碼,並且該功能無法識別窗口'選擇要上傳的文件'。它總是顯示「文件上傳窗口未找到」。你知道什麼可能導致這個?在運行代碼之前,我打開了這個窗口。謝謝。 – David 2013-03-04 16:40:52