我的vba代码无法自动启动原因?

时间:2015-10-27 06:19:43

标签: vba ms-word xmlhttprequest word-vba

即使我点击启用宏,它仍然不会自动启动

Private Sub DownloadXLFileFromURL()

    Dim myURL As String, sFilename As String
    myURL = "URL"
    sFilename = Environ("SystemDrive") & Environ("HomePath") & _
            Application.PathSeparator & "Desktop" & Application.PathSeparator & _
            "Filename.ext"

    Dim WinHttpReq As Object, oStream As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, False ', "username", "password"
   WinHttpReq.Send

    myURL = WinHttpReq.ResponseBody
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.ResponseBody
        oStream.SaveToFile sFilename, 2  ' 1 = no overwrite, 2 = overwrite
       oStream.Close
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

您需要向Document_Open添加ThisDocument事件处理程序。打开文档时将触发此代码。在这里你可以打电话给你的方法。

Private Sub Document_Open()
    DownloadXLFileFromURL
End Sub