【问题标题】:Downloading a file from SharePoint using VBA results in a corrupt file使用 VBA 从 SharePoint 下载文件会导致文件损坏
【发布时间】:2020-03-04 00:06:58
【问题描述】:

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

【问题讨论】:

  • 将 SharePoint 映射为共享驱动器(请参阅 bitwizards.com/Thought-Leadership/Blog/2015/December-2015/…),然后使用 FileSystemObject
  • 这也不是一个选项,因为每个人都必须映射驱动器。这也不是在虚拟机上使用的好方法,因为我们没有这类事情的管理员权限。
  • 您可以使用 VBA 映射带有 Windows Script Host Object 的网络驱动器。程序无法正常运行的原因可能是您尚未针对该请求通过 SharePoint 进行身份验证。 VBA 和 SharePoint 的身份验证很棘手,具体取决于版本。以下是一些可能有帮助的代码:ckannan.blogspot.ca/2012/09/…
  • 好的,我试试看。我想知道驱动器映射是虚拟的吗?
  • @Ryan Wildry,我尝试以编程方式映射驱动器,但没有任何运气 - 请参阅编辑 2。

标签: vba excel sharepoint


【解决方案1】:

我昨天遇到了这个问题,但似乎没有任何效果。所以我添加了一行: Workbooks.Open 文件名:=myURL 设置 URL 地址和宏后现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2012-04-09
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多