简体   繁体   English

如何从 my.sharepoint.com (onedrive) 下载 Excel 文件

[英]How to download Excel file from my.sharepoint.com (onedrive)

I have an Excel file which is shared via Onedrive link.我有一个通过 Onedrive 链接共享的 Excel 文件。 I need to download this file to PC (c:\\TEST).我需要将此文件下载到 PC (c:\\TEST)。

I found this code, it downloaded the file, but the file is corrupted or something.我找到了这段代码,它下载了文件,但文件已损坏或什么的。

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

ERROR:错误: 下载后报错

Try the following code (I got it very likely from here as stated in Tragamor's comment)试试下面的代码(我很可能从这里得到它,如 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

Then you only need to那么你只需要

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

Thanks to @Storax I find the answer to my problem.感谢@Storax,我找到了问题的答案。 Whole problem was in the link that was given me from Onedrive.整个问题出在 Onedrive 给我的链接中。 I follow steps from this site and file is working now :)我按照此站点的步骤操作,文件现在正在运行:)

Thank you Storax again再次感谢 Storax

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM