首页 > 解决方案 > 将谷歌脚本结果下载到 Excel VBA

问题描述

我有一个应该将数据传输到 Excel 文件的 webApp(谷歌表格)。

在脚本中,我目前正在使用 ContentService.createTextOutput() 返回一些内容,请参阅链接

在 VBA 中我尝试了不同的代码,例如

Sub Test()
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", "https://script.google.com/macros/s/AKfycbxU2ZL39IdtMzQXu0OLJZz3shSOx1JNTCbe1_SCxunIimLJVqY/exec", False
WinHttpReq.Send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.ResponseBody
    oStream.SaveToFile "c:\test.txt", 2
    oStream.Close
End If
End Sub

使用运行时错误 70,我也尝试使用 WinHttp.WinHttpRequest.5.1 但出现其他错误(我想超时)

我可以使用此链接毫无问题地下载整个文件,我看到 ContentService 重定向浏览器页面(并且直接下载没有)但我真的不知道如何使用 VBA 处理它(而且我没有找到任何东西有用的谷歌搜索)

感谢帮助

标签: vbagoogle-apps-script

解决方案


经过数小时的尝试和提出问题后的 10 分钟,我现在找到了 InternetExplorer.Application 的解决方案

Sub Test2()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object

'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = False

'Define URL
URL = "https://script.google.com/macros/s/AKfycbxU2ZL39IdtMzQXu0OLJZz3shSOx1JNTCbe1_SCxunIimLJVqY/exec"

'Navigate to URL
IE.Navigate URL

' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop   'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop   'Do Until
MsgBox (IE.document.body.innerText)

'Unload IE
Set IE = Nothing
End Sub

推荐阅读