【问题标题】:How to download Excel file from my.sharepoint.com (onedrive)如何从 my.sharepoint.com (onedrive) 下载 Excel 文件
【发布时间】:2020-10-14 12:06:31
【问题描述】:

我有一个通过 Onedrive 链接共享的 Excel 文件。我需要将此文件下载到 PC (c:\TEST)。

我找到了这段代码,它下载了文件,但是文件损坏了。

Sub DownloadFile()
    MsgBox ("12")
    Dim myURL As String
    myURL = "https://foxhunter1-my.sharepoint.com/:x:/g/personal/name_example/Eexy0m7o08hBlRJAP_xh64wBN45j70JIw2E-CDlJGgZILg?e=cbs4iF"

    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    With WinHttpReq
        WinHttpReq.Open "GET", myURL, False, "contoso\user", "password"
        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\TEST.xlsx", 2 ' 1 = no overwrite, 2 = overwrite
            oStream.Close
        End If
    End With
End Sub

错误:

【问题讨论】:

  • 你确定链接是正确的,如果是,你确定它真的是一个 XLSX 文件吗?
  • 链接正确,在任何浏览器都可以打开,是.xlsx文件。
  • 在我回答下面的讨论之后,我很确定该链接不是下载文件的正确链接。它只是在浏览器中打开文件的链接。您需要获取文件的直接链接,该文件还应包含以 xlsx 结尾的 Excel 文件名。

标签: excel vba onedrive


【解决方案1】:

试试下面的代码(我很可能是从 here 得到的,正如 Tragamor 的评论中所说)

Option Explicit
#If VBA7 Then
    Private Declare PtrSafe 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
#Else
    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
#End If  

    Function DownloadFileFromWeb(strURL As String, strSavePath As String) As Long

        ' strSavePath includes filename
        DownloadFileFromWeb = URLDownloadToFile(0, strURL, strSavePath, 0, 0)
    End Function

那么你只需要

Sub GetFile()
    Dim urlName  As String
    urlName = "your Url"
    Dim fName As String
    fName = "C:\TEST\test.xlsx"
    URLDownloadToFile 0, urlName, fName, 0 , 0

End Sub

【讨论】:

  • 如果您使用,请链接资源。这是来自这里:stackoverflow.com/questions/42419486/…
  • 当我复制你的代码时,“Privete Declare... to ...) As Long”的部分是红色的。如果我使用我的 URL 运行 Sub GetFile(),我会收到编译错误:必须更新此项目中的代码才能在 64 位系统上使用。请查看并更新 Declare 语句,然后使用 PtrSafe 属性对其进行标记。
  • 好的,给我一点时间来调整 64 位 Excel 的代码,但是如果你知道怎么做,为什么不做呢?
  • @Tragamor:你可能是对的,我得到了它,但我从我的代码库中复制了它。这就是我迷路的原因:-(
  • 所以,您还没有得到 xlsx 文件的直接链接。您需要先获取正确的链接,然后才能下载文件。例如,您在共享点上直接在 Excel 中打开文件,打开 VBE 并使用 ThisWorkbook.Fullname 检索全名。
【解决方案2】:

感谢@Storax,我找到了问题的答案。整个问题出在 Onedrive 给我的链接中。 我按照site 中的步骤操作,文件现在可以工作了:)

再次感谢 Storax

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2017-10-09
    • 2022-12-16
    相关资源
    最近更新 更多