2

我有这个问题。

我有一个需要上传文件的页面。当我单击“浏览器”时,“选择要上传的文件”窗口打开,我需要选择(双击)一个 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
4

1 回答 1

2

您必须使用 API 与该窗口进行交互,方法是找到名称为“ Choose File To Upload ”的窗口

这是一个例子

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

锁定到相关窗口后,您必须找到其中HandleTextbox,然后将带有完整路径的文件名粘贴到那里。完成后,您会找到OpenButton 的句柄并最终单击它。

我在这里广泛地介绍了它。尽管在我在链接中发布的示例中,我正在使用保存文件,Save As但您必须使用相同的方法来查找句柄并上传文件。

高温高压

于 2013-02-15T16:49:13.663 回答