如何使用VBA控制已经打开的Web文件对话框?

我试图在我公司的Intranet站点上传一个图片。 但它打开一个FileDialog,我需要select一些文件,然后单击“确定”button。 但我不想用sendKeys来做。 有谁知道如何用VBA来控制这些Microsoft Windows FileDialog。 只是“文件名”字段,和确定button。

对不起,如果我没有任何代码。 这是因为我找不到任何人。 不知道。

最有效的方法是通过XHR上传文件。 在您的浏览器中打开开发人员工具,networking选项卡,打开Intranet网站网页,照常上传文件。 然后,根据上次logging的POST请求的参数,可以构build相同的XHR。

作为一个例子,下面是实现了一个最简单的webform的function的代码,其中包含唯一的文件types的字段:

Sub UploadTest() Dim strUplStatus, strUplResponse UploadFile "C:\image.jpg", strUplStatus, strUplResponse MsgBox strUplStatus & vbCrLf & strUplResponse End Sub Sub UploadFile(strPath, strStatus, strResponse) Dim strFile, strExt, strContentType, strBoundary, bytData, bytPayLoad On Error Resume Next With CreateObject("Scripting.FileSystemObject") If .FileExists(strPath) Then strFile = .GetFileName(strPath) strExt = .GetExtensionName(strPath) Else strStatus = "File not found" Exit Sub End If End With With CreateObject("Scripting.Dictionary") .Add "txt", "text/plain" .Add "html", "text/html" .Add "php", "application/x-php" .Add "js", "application/x-javascript" .Add "vbs", "application/x-vbs" .Add "bat", "application/x-bat" .Add "jpeg", "image/jpeg" .Add "jpg", "image/jpeg" .Add "png", "image/png" .Add "exe", "application/exe" .Add "doc", "application/msword" .Add "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" .Add "xls", "application/vnd.ms-excel" .Add "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" strContentType = .Item(LCase(strExt)) End With If strContentType = "" Then strStatus = "Invalid file type" Exit Sub End If With CreateObject("ADODB.Stream") .Type = 1 .Mode = 3 .Open .LoadFromFile strPath If Err.Number <> 0 Then strStatus = Err.Description & " (" & Err.Number & ")" Exit Sub End If bytData = .Read End With strBoundary = String(6, "-") & Replace(Mid(CreateObject("Scriptlet.TypeLib").GUID, 2, 36), "-", "") With CreateObject("ADODB.Stream") .Mode = 3 .Charset = "Windows-1252" ' Latin .Open .Type = 2 .WriteText "--" & strBoundary & vbCrLf .WriteText "Content-Disposition: form-data; name=""upload_file""; filename=""" & strFile & """" & vbCrLf .WriteText "Content-Type: """ & strContentType & """" & vbCrLf & vbCrLf .Position = 0 .Type = 1 .Position = .Size .Write bytData .Position = 0 .Type = 2 .Position = .Size .WriteText vbCrLf & "--" & strBoundary & "--" .Position = 0 .Type = 1 bytPayLoad = .Read End With With CreateObject("MSXML2.XMLHTTP") .Open "POST", "http://mysite/upload.php", False .SetRequestHeader "Content-type", "multipart/form-data; boundary=" & strBoundary .Send bytPayLoad If Err.Number <> 0 Then strStatus = Err.Description & " (" & Err.Number & ")" Else strStatus = .StatusText & " (" & .Status & ")" End If If .Status = "200" Then strResponse = .ResponseText End With End Sub