如何使用VBA从SharePoint下载文件?

问题描述 投票:0回答:3

我正在尝试使用 VBA 从 SharePoint 下载文件。

该文件是一张图片,但该图片一旦进入系统就无法查看。

我认为我下载的格式错误。

Sub DownloadFromSharepoint()
    Dim myURL As String
    myURL = "https://MYSHAREPOINTSITE"

    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, 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:\Users\DOMAIN\temp.jpg")
        oStream.Close
    End If
End Sub
excel vba sharepoint
3个回答
8
投票

这是我当前用于从 Sharepoint 站点下载文件的包装器代码:

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

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

如果下载成功,DownloadFileFromWeb 函数返回 0。


0
投票

URLDownloadToFile 函数对我不起作用。它下载了一些 html 代码而不是 Excel 文件

仅对于 Excel 文件,我使用 Excel.Application 对象在后台打开文件,然后将其保存在本地文件夹中:

Public Sub DownloadExcelFileFromSharepoint(ByVal SharepointFileRoute As String, ByVal TargetDestinationFile As String)
    'No neccesary reference to Microsoft Excel Object Library, using late binding

    Dim oExcelApplication As Object 'Excel.Application
    Dim oExcelWorkbook As Object 'Excel.Workbook

    Set oExcelApplication = CreateObject("Excel.Application")
    Set oExcelWorkbook = oExcelApplication.Workbooks.Open(SharepointFileRoute, ReadOnly:=True)

    ' Don't display alerts on saving, so if TargetDestinationFile exists will be overwrited
    oExcelApplication.DisplayAlerts = False
    oExcelWorkbook.SaveAs TargetDestinationFile
    oExcelApplication.DisplayAlerts = True

    oExcelWorkbook.Close
    Set oExcelWorkbook = Nothing
    
    oExcelApplication.Quit
    Set oExcelApplication = Nothing
End Sub

获取正确的 URL 对我来说并不明显。在浏览器中打开文件时仅复制 Sharepoint 的 URL 并将其与此功能一起使用是行不通的。我必须使用打开文件对话框在 Excel 中打开文件,写入 shareponit 文件夹并导航到文件子文件夹。我有这样的东西:

https://michelingroup.sharepoint.com/sites/TestSite/Shared documents/TestFile.xlsx

0
投票

这里给出的2个答案毫无价值。他们没有提供有关如何设置共享点文件夹和文件的信息,也没有提供文件保存位置的信息。只是浪费时间。

© www.soinside.com 2019 - 2024. All rights reserved.