Access VBA调用xmlhttp和ADODB.Stream来下载远程文件

2017-08-27 09:50:00
zstmtony
原创
545

Access VBA调用xmlhttp和ADODB.Stream来下载远程文件


1.新建一个Access数据库文件,然后添加引用 
   Microsoft scripting runtime,Microsoft Active Data Object,Microsoft MsXml
  如果不想前期引用,也可使用CreateObject方法
 
2.新建一个窗体Form1
  窗体代码如下:
Public xmlHttp As MSXML2.XMLHTTP
Private Sub Command1_Click()
   Dim cls As clsSaveFile
   Set xmlHttp = New MSXML2.XMLHTTP
   xmlHttp.open "get", "http://www.ljc.com/sll.exe", True
   Set d = New Class1
   xmlHttp.Onreadystatechange = d
   xmlHttp.send
End Sub     



3.类模块 clsSaveFile 代码:

Dim b As ADODB.Stream
Dim fso As Scripting.FileSystemObject
Public curReadyState As Long
Public Function DoIt()
  Debug.Print Form1.xmlHttp.readyState
  If Form1.xmlHttp.readyState = 4 Then
     SaveFile
  End If
End Function
Public Function SaveFile()
   Set adoSm = New ADODB.Stream
   adoSm.Type = 1
   adoSm.open
   Set fso = New Scripting.FileSystemObject
   If Form1.xmlHttp.readyState = 4 Then
        adoSm.Write (Form1.xmlHttp.responseBody)
        If Not fso.FileExists("c:\office-cn.jpg") Then
           adoSm.SaveToFile "c:\office-cn.jpg"
        End If
   End If
   adoSm.Close
   Set adoSm = Nothing
    
   Set fso = Nothing
End Function


注意将clsSaveFile的DoIt设置成default的。
分享