24

Usually I use this piece of code to retrieve the content of a folder in VBA. But this doesn't work in the case of a sharepoint. How can I do ?

Dim folder As folder
Dim f As File
Dim fs As New FileSystemObject

Set folder = fs.GetFolder("//sharepoint.address/path/to/folder")

For Each f In folder.Files
    'Do something
Next f

EDIT (after a good comment by shahkalpesh) :

I can access to the sharepoint if I enter the address in Windows Explorer. Access to the sharepoint needs an authentification, but it's transparent, because it relies on the Windows login.

afewcc
  • 1,077
  • 3
  • 9
  • 20

11 Answers11

18

The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.

Add references to the following ActiveX libraries in VBA:

  • Windows Script Host Object Model (wshom.ocx) - for WshNetwork
  • Microsoft Scripting Runtime (scrrun.dll) - for FileSystemObject

Create a new class module, call it DriveMapper and add the following code:

Option Explicit

Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork

Private Sub Class_Terminate()
  UnmapDrive
End Sub

Public Function MapDrive(NetworkPath As String) As Scripting.Folder
  Dim DriveLetter As String, i As Integer

  UnmapDrive

  For i = Asc("Z") To Asc("A") Step -1
    DriveLetter = Chr(i)
    If Not oFSO.DriveExists(DriveLetter) Then
      oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
      Set oMappedDrive = oFSO.GetDrive(DriveLetter)
      Set MapDrive = oMappedDrive.RootFolder
      Exit For
    End If
  Next i
End Function

Private Sub UnmapDrive()
  If Not oMappedDrive Is Nothing Then
    If oMappedDrive.IsReady Then
      oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
    End If
    Set oMappedDrive = Nothing
  End If
End Sub

Then you can implement it in your code:

Sub test()
  Dim dm As New DriveMapper
  Dim sharepointFolder As Scripting.Folder

  Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")

  Debug.Print sharepointFolder.Path
End Sub
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Chris Hayes
  • 3,876
  • 7
  • 42
  • 72
  • can be tricky to map network drive; I found [how-to-map-sharepoint](http://stemrc.aihec.org/SharePoint%20Tips%20and%20Tricks/Creating%20a%20Windows%20Drive%20Mapping%20for%20a%20SharePoint%20Document%20Library.pdf) useful to resolve this. – Adriaan Jan 16 '12 at 14:53
  • 1
    This code looks very promising but `Sub test()` is throwing a "User-defined type not defined" compile error for the `Dim dm as New DriveMapper` line. Perhaps I am missing a DLL reference? I've added Microsoft Scripting Runtime and also Windows Script Host Object Model. Using Excel 2010. – Shrout1 Sep 10 '13 at 14:47
  • sorry for responding so late @shrout1, maybe you made a module instead of a class? – Chris Hayes Jan 11 '16 at 21:38
  • Thanks for great workaround. By connecting directly I had to manually "visit" the sharepoint site before getting active connection, but mapping drive seems to solve that issue. One question: how can I avoid unmapping drive before my code, that calls DriveMapper class, finishes? I'm not very familiar with how they work yet. – Trm Apr 05 '16 at 11:35
  • @Trm someone edited my post to wrap the code in a class with a dispose method "Class_Terminate" which unmaps the drive. When the class goes out of scope then the drive get's unmapped. You could just remove the "Class_Terminate" method... – Chris Hayes Apr 11 '16 at 18:04
  • @ChrisHayes yea, I figured as much. I removed it and then was stuck with bunch of mapped drives every-time I opened connection. I did some workaround by saving mapped drive letter to memory and unmapping at the end of sub in module. Not sure if it's the most elegant solution. – Trm Apr 11 '16 at 18:07
16

Use the UNC path rather than HTTP. This code works:

Public Sub ListFiles()
    Dim folder As folder
    Dim f As File
    Dim fs As New FileSystemObject
    Dim RowCtr As Integer

    RowCtr = 1
    Set folder = fs.GetFolder("\\SharePointServer\Path\MorePath\DocumentLibrary\Folder")
    For Each f In folder.Files
       Cells(RowCtr, 1).Value = f.Name
       RowCtr = RowCtr + 1
    Next f
End Sub

To get the UNC path to use, go into the folder in the document library, drop down the Actions menu and choose Open in Windows Explorer. Copy the path you see there and use that.

Chris Latta
  • 20,316
  • 4
  • 62
  • 70
11

In addition to:

myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")

also replace space:

myFilePath = replace(myFilePath, " ", "%20")
Martin.
  • 10,494
  • 3
  • 42
  • 68
Eileen
  • 111
  • 1
  • 2
2

I messed around with this problem for a bit, and found a very simple, 2-line solution, simply replacing the 'http' and all the forward slashes like this:

myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")

It might not work for everybody, but it worked for me

If you are using a secure site (or wish to cater for both) you may wish to add the following line:

myFilePath = replace(myFilePath, "https:", "")
New Alexandria
  • 6,951
  • 4
  • 57
  • 77
  • 1
    Actually, the above seems to be incomplete for me and should read for https: (in addition to the above code) `myFilePath = Replace(myFilePath, Split(myFilePath, "\")(2), Split(myFilePath, "\")(2) & "@SSL")` this will convert `https://my.SharePoint.com/` eventually to `\\my.SharePoint.com@SSL\ ` (after all the replaces). – Ralph Mar 20 '19 at 16:10
2

IMHO the coolest way is to go via WebDAV (without Network Folder, as this is often not permitted). This can be accomplished via ActiveX Data Objects as layed out in this excellent article excellent article (code can be used directly in Excel, used the concept recently).

Hope this helps!

http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic/

the original link is dead, but at least the textual content is still available on archive.org: http://web.archive.org/web/20091008034423/http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic

MostlyHarmless
  • 445
  • 2
  • 11
  • 21
BigD
  • 372
  • 2
  • 7
  • 5
    As of 02/07/2013, this article link seems to be dead. Does anyone know if this article is still around else where? – armstrhb Feb 07 '13 at 16:19
  • 1
    @armstrhb: there is a copy on www.archive.org, but there seems to be only the text available, not the graphics. – MostlyHarmless Jun 05 '15 at 03:48
1

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

  • Link is dead!!! – blablubbb Nov 09 '22 at 12:25
  • 1
    @blablubb Alright, here are some updated links for you. Note that these links might change once I get around to rebuilding my website. It went through a Big Ugly Meltdown a while ago and I've been a very lazy person. http://stevenbritton.net/excel-vba-soap-xml-and-sharepoint-verify-a-file-exists/ Note that the original implementation stopped working when SharePoint got updated, and it turned around and failed quietly... http://stevenbritton.net/excel-and-sharepoint-revisited/ – Steven C. Britton Nov 12 '22 at 18:17
1

Mapping the WebDAV folder is my preferred method of creating an easily accessible, long-term connection to SharePoint. However, you'll find—even when properly mapped—that a file will return a URL when selected (especially via Application.FileDialog) due to changes in Windows 10 1803.

To circumvent this, you can map the drive using DriveMapper (or an equivalent) and then combine the resulting Application.FileDialog.SelectedItems with a URL to UNC converter function:

Public Function SharePointURLtoUNC( _
  sURL As String) _
As String
  Dim bIsSSL As Boolean

  bIsSSL = InStr(1, sURL, "https:") > 0
  sURL = Replace(Replace(sURL, "/", "\"), "%20", " ")
  sURL = Replace(Replace(sURL, "https:", vbNullString), "http:", vbNullString)
  
  sURL= Replace(sURL, Split(sURL, "\")(2), Split(sURL, "\")(2) & "@SSL\DavWWWRoot")
  If Not bIsSSL Then sURL = Replace(sURL, "@SSL\", vbNullString) 
  SharePointURLtoUNC = sURL
End Function
mpdrsn
  • 21
  • 1
  • 3
1

Here's a code that works for me:

Note...to get the URL part that has @SSL what you need to do is to copy the url of the sharepoint folder from Microsoft Edge/Chrome into Windows file explorer...then right click the current folder -> Properties and that should show you the path that has @SSL that you should use. That's the most difficult part!

enter image description here

Sub GetAllFileNamesInSharePointFolder()

FileName = Dir("\\mycompany.sharepoint.com@SSL\DavWWWRoot\teams\NCICDS\Testing folder for Me\Elise\Deal Docs\2022\Metro Egypt\Confectionery\*.*")

Do While FileName <> ""
    Debug.Print FileName
    FileName = Dir()
Loop
End Sub
user2465349
  • 83
  • 1
  • 1
  • 8
Chadee Fouad
  • 2,630
  • 2
  • 23
  • 29
  • Of all the answers on this post, this one actually works for Modern SharePoint sites and is simple to setup. I don't have to worry about mapping a network drive or create another surrogate process to refresh an expired connection. I also don't have to enable some special VBA reference library either. Verified to work as of April 2022. – user2465349 Apr 02 '22 at 21:35
  • @user2465349 Thanks! Glad that this helped. However, Microsoft recommends syncing files to your computer as a more stable and more reliable solution. Once that is done you can scan it just like any other directory on your harddisk. Check this out: https://support.microsoft.com/en-us/office/sync-sharepoint-files-and-folders-87a96948-4dd7-43e4-aca1-53f3e18bea9b – Chadee Fouad Apr 06 '22 at 02:57
1

Drive mapping to sharepoint (also https)

Getting sharepoint contents worked for me via the mapped drive iterating it as a filesystem object; trick is how to set up the mapping: from sharepoint, open as explorer Then copy path (line with http*) (see below)

address in explorer

Use this path in Map drive from explorer or command (i.e. net use N: https:://thepathyoujustcopied) Note: https works ok with windows7/8, not with XP.

That may work for you, but I prefer a different approach as drive letters are different on each pc. The trick here is to start from sharepoint (and not from a VBA script accessing sharepoint as a web server).

Set up a data connection to excel sheet

  • in sharepoint, browse to the view you want to monitor
  • export view to excel (in 2010: library tools; libarry | export to Excel) export to excel
  • when viewing this excel, you'll find a datasource set up (tab: data, connections, properties, definition)

connection tab

You can either include this query in vba, or maintain the database link in your speadsheet, iterating over the table by VBA. Please note: the image above does not show the actual database connection (command text), which would tell you how to access my sharepoint.

Adriaan
  • 3,282
  • 1
  • 23
  • 31
0

A better and more stable solution is to sync sharepoint to your hardsisk. Once that is done you can use DIR function to scan files just like other files on your hardisk. Check out this video from Microsoft regarding how to do this: https://support.microsoft.com/en-us/office/sync-sharepoint-files-and-folders-87a96948-4dd7-43e4-aca1-53f3e18bea9b

Chadee Fouad
  • 2,630
  • 2
  • 23
  • 29
-3

Try mapping the sharepoint library to a drive letter in windows. Then select the drive and path in your code.