Manipulate IE with VBA and a modal form

2019-07-27 21:48发布

问题:

I'm trying to automate the uploading of an excel document to a particular webpage. I can't link it as it requires an account. There is a form with a an browse section (of type=file so I can't just set the value) and an upload button that uses the value of that input.

I can navigate to click the browse button, and I can click the upload button, but when I click the browse button a file explorer window called "Choose File to Upload" pops up and means I can't interact with any other IE window and pauses my VBA code until it is closed, which means I can't automatically pass a file path to it.

The relevant HTML on the page is

<form method="post" name="uploadSkillForm" ENCTYPE="multipart/form-data"  action='uploadSkills.do?operation=upload'>        

  <tr>

</tr> 

<tr class="text1">

</tr> 


<tr width="100%">
    <td colspan="100%">
        <table width="100%">
            <tr>
                <th align="left" colspan=3 width="60%">
                    <input type="file" name="uploadedFile"  size="34" id="filePath" class="buttonStyle" style="height:20px"/>&nbsp;&nbsp;
                    <input type="button" name="upload" class="buttonStyle" value="Upload" onclick="javascript:fnUploadData()">
                </th>
            </tr>
        </table>
    </td>
</tr>

Ideally I just want to be able to keep the VBA running and interact with the dialog box to put in the file path, but any way to get the value set to the path would do.

The VBA currently just opens the webpage and clicks the button so there is no point posting it.

Any help would be really appreciated!

回答1:

So after much digging I decided that I had to just have VBA run an external script that checks for the window and input the file name then presses enter. Currently the issue is that it focuses on the file window so if you aren't in the right folder it doesn't work, but if you are it will select the right file and click open!

The vba:

Dim retval As Variant
retval = Shell("PowerShell .'" & path & "upload_tester.ps1 file_name'", 1)

where the path is where it is stored, upload_tester.ps1 is the script name and file_name is to pass to the script to input to file browser.

The script:

param(
[Parameter(Mandatory=$true)][string]$a
)

$wshell = new-object -com wscript.shell

while(! $wshell.appactivate("Choose File to Upload")){
start-sleep -milliseconds 100
}

$wshell.appactivate("Choose File to Upload")
start-sleep -milliseconds 500;
$wshell.sendkeys($a)
$wshell.sendkeys("{ENTER}")

This will check until the file explorer window is open, type in the file name to match it, and then press enter to select it. If anyone knows how to get it to focus on the text box part rather than the file explorer part that would be great but otherwise this works for my purpose!