使用VBA从SharePoint下载文件会导致文件损坏

时间:2018-02-19 07:59:43

标签: vba excel-vba sharepoint excel

我想编写一个宏,它将从我们的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


Sub Button1_Click()

   DownloadFileFromWeb = URLDownloadToFile(0, 
   "https://our.sharepoint.com/sharedFolder/file.pptx", "C:\Users\User\folder\myfile.pptx", 0, 0)
   Debug.Print DownloadFileFromWeb

End Sub

代码来自:How to download a file from Sharepoint with VBA

URLDownloadFile返回的值为0,但是当我打开文件时,PowerPoint要求我修复它。理想情况下,我希望用户只需登录SharePoint,然后使用此宏下载共享文件的新副本。我的猜测是它与身份验证有关,但我不知道如何解决这个问题,因为我在这方面没有太多经验。我绝对不想提示凭据并将它们作为纯文本传递给函数,我也不希望用户在某处硬编码。我希望用户登录到SharePoint以及代码来完成剩下的工作。任何有关此事的帮助将不胜感激。

编辑: 我还尝试使用以下代码生成相同的损坏文件。看起来凭证可能不是问题。

Dim myURL As String
myURL = "https://our.sharepoint.com/sharedFolder/file.pptx"

Dim WinHttpReq 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 "C:\Users\User\folder\myfile.pptx", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

EDIT2:

我尝试使用包括net useNew-psdrive在内的各种命令映射驱动器而没有任何运气 - 我仍然无法进行身份验证。这是一个PowerShell命令及其输出

net use S: '\\out.sharepoint.com/Shared Library' password /USER:me@domain.us

System error 1244 has occurred.

The operation being requested was not performed because the user has not 
been authenticated.

1 个答案:

答案 0 :(得分:0)

昨天我遇到了这个问题,似乎什么也没用。所以我添加了一行: Workbooks.Open文件名:= myURL 设置URL地址和宏后,现在可以正常使用了。