How to traverse folders and files on SharePoint with Excel VBA

pczegle

New Member
Joined
Nov 24, 2010
Messages
24
I have done many searches on how to traverse all files in SharePoint folders using Excel VBA and have not come across an answer I could use because, by configuration design, I cannot map a SharePoint URL to a drive letter. After much trial and error, I came up with a very short solution that works for me. I'd like to share it in thanks for all the help I have gotten by searching forums like this one. I hope it helps you get home to your kids a little sooner. Here it is:

Sub SPDir()
Dim wb As Workbook
Dim dummyFile As String
'
' The file specified by dummyFile must reside in SharePoint in order to use SharedWorkspace
' The way the code is set up, the path and filename in dummyFile should NOT substitute %20 instead of spaces
' There is logic later to ignore dummyFile on output
' Substitute your own dummy file name below
' If you don't want to create a dummy file on SharePoint, pick any file that's already there
' and get rid of the logic below that ignores it.
'
dummyFile = "https://........"
Set wb = Workbooks.Open(dummyFile)
Application.Wait Now + TimeValue("00:00:01") ' if this code terminates abnormally, try a longer wait value
Set swsFiles = wb.SharedWorkspace.Files
For Each c In swsFiles
'
' The Path logic below limits traversing to just the folder that contains
' dummyFile and all its sub-folders. This can be changed to suit needs.
'
If Replace(c.URL, "%20", " ") <> dummyFile And _
Left(Replace(c.URL, "%20", " ") , Len(wb.Path)) = wb.Path Then MsgBox (c.URL)
Next c
End Sub
 
For some reason I am getting an "Object variable or With block variable not set" error on this line.

Code:
Set swsFiles = wb.SharedWorkspace.Files

Anyone know why?

Ken,
I'm not an Excel or Sharepoint guru and it's been a while since I looked at this. While I can't promise that I can get this to work for you, let's see if I can help.

First, the code was written while I was using Excel 2003. I now notice that for Excel 2010, the following note is provided at http://msdn.microsoft.com/en-us/library/ff862502.aspx for the SharedWorkspace Object:
Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

So the first question is what version of Excel are you using? If your at 2003 or 2007 you should be good. If you're at 2010 maybe not.

Next, while the SharedWorkspace.Files method is short, I later discovered that it restricts the number of files returned to 99 and it will return nothing if that's exceeded. If you like, there's a more elaborate method documented further down that doesn't have these limitations. It requires the Microsoft ActiveX Data Objects 2.x Library which you can research. I'm at Excel 2007 and this method works fine with it.

Otherwise, if you're sure you prefer the SharedWorkspace.Files method, it requires a seed file (which can be a dummy file that's not used for anything else) at the root folder of your Sharepoint search tree. Once you put your seed file there, set the dummyFile variable to point to that seed file as follows:
dummyFile = "https://......../your_seed_file_name.typ"

The seed file is specifically eliminated from the returned search tree because it's assumed to be a dummy file. You can easily change this in the code for yourself if you like.

It sounds to me like you might get an obect error if the open of the seed file performed by the statement, Set wb = Workbooks.Open(dummyFile), was not successful. If the problem persists even after you're sure the setup is correct, then try single stepping through the macro code execution to make sure the open worked.
 
Upvote 0

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
I am using Excel 2010, but the "seed" file definitely opened...but maybe it opened not as a sharepoint file but as a "downloaded" file for lack of a better term. It definitely blew up on the line indicated.

I'll keep researching.

Ken,
I'm not an Excel or Sharepoint guru and it's been a while since I looked at this. While I can't promise that I can get this to work for you, let's see if I can help.

First, the code was written while I was using Excel 2003. I now notice that for Excel 2010, the following note is provided at http://msdn.microsoft.com/en-us/library/ff862502.aspx for the SharedWorkspace Object:
Beginning with Microsoft Office 2010, this object or member has been deprecated and should not be used.

So the first question is what version of Excel are you using? If your at 2003 or 2007 you should be good. If you're at 2010 maybe not.

Next, while the SharedWorkspace.Files method is short, I later discovered that it restricts the number of files returned to 99 and it will return nothing if that's exceeded. If you like, there's a more elaborate method documented further down that doesn't have these limitations. It requires the Microsoft ActiveX Data Objects 2.x Library which you can research. I'm at Excel 2007 and this method works fine with it.

Otherwise, if you're sure you prefer the SharedWorkspace.Files method, it requires a seed file (which can be a dummy file that's not used for anything else) at the root folder of your Sharepoint search tree. Once you put your seed file there, set the dummyFile variable to point to that seed file as follows:
dummyFile = "https://......../your_seed_file_name.typ"

The seed file is specifically eliminated from the returned search tree because it's assumed to be a dummy file. You can easily change this in the code for yourself if you like.

It sounds to me like you might get an obect error if the open of the seed file performed by the statement, Set wb = Workbooks.Open(dummyFile), was not successful. If the problem persists even after you're sure the setup is correct, then try single stepping through the macro code execution to make sure the open worked.
 
Upvote 0
I am using Excel 2010, but the "seed" file definitely opened...but maybe it opened not as a sharepoint file but as a "downloaded" file for lack of a better term. It definitely blew up on the line indicated.

I'll keep researching.

A couple of things:

1-The seed file must be in the root folder of your search tree on SharePoint and the dummyFile variable must point to that SharePoint location. It won't help to download it first and then point to the downloaded copy.

2-This method works with Excel 2003 and should work with 2007 as well. If you have availability to one of these versions, try it there first to make sure there are no esoteric SharePoint configurational issues at your site.

3-The version of SharePoint on the server side might also be an issue. I'm not even sure what version my workplace is at ... probably 2003 ... maybe 2007. If everything at your site is the latest and greatest, there might be newer methods available in VBA that are synchronized with your version of the SharePoint server that accomplish similar results. I'd be surprised if MS took away this method without replacing it with something better. Who knows, there might even be a MS utility at your version level that does what you need without requiring any programming.
 
Upvote 0
Thanks for all the ideas. I keep trying to find what they replaced it with for 2010 but have not found any answers yet. I will answer back if I find anything.
 
Upvote 0
pczegle,

Your code really helped for a few years. It stopped working recently and gives errors on the first "davdir.open" command. Do you have any ideas? Thank you.
 
Upvote 0
I have used this code running Windows XP many times. It worked great! I didn't have to change anything.

Recently I was upgraded to Windows 7. Now when I run this code, I get this error.

=====
Err.number = -2147217895</SPAN>
Err.description = : Object or data matching the name, range, or selection criteria was not found within the scope of this operation</SPAN></SPAN>.
=====


In my debugging efforts, I have discovered that the code is stopping on this line:

davDir.Open "", _
tempURL, _
adModeReadWrite, _
adFailIfNotExists, _
adDelayFetchStream ', _
' "username", _
' "password"


Has anyone else seen this before? Any ideas what the problem/resolution is?

I had a coworker try it on his Windows 7 machine and he got the same error.

Any guidance on on this would be greatly appreciated!!


thanks,
dennis
 
Upvote 0
The following VBA code produces a folder/file tree of the specified Sharepoint Site. Unlike the SharedWorkspace.Files method, it does NOT restrict the number of files & folders to 99 in order to produce a list. It requires using the Microsoft ActiveX Data Objects 2.x Library (I used 2.8) . If it's NOT installed, research the web on how to install it. If it is installed, activate it by selecting "Tools" and then "References" in the VB editor/debugger. Then click on the checkbox for this library.

Code was borrowed and adapted from several places:
1 - http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic/
author Jeffrey Ridout provided the basic code to use the webDav methodology
2 - ADO GetChildren Method
provided code to restrict the contents of subfolders to where davDir.RecordType = adCollectionRecord to potentially avoid error code 3001 when using the GetChildren method.

The only thing I did was to modify the code to produce the tree listing in recursive fashion to handle all the nested subfolders.

Please note that I am not an Excel VBA guru. If you want to improve this code, that's great!

I hope this helps you.

Public Stack As New Collection
Public PrintLine As String
Public Spaces As String
Public fnum As Integer
Public outputFile As String
'
' Stack provides a means of storing the folder/file tree for followup processing, if necessary.
' It's not used actively by this program. Please note that the VB editor/debugger will only
' display the first 256 Stack entries even though there are potentially many more.
'
Sub NavigateSharepointSite()
'
' outputFile is where the folder/file tree is written
' spSite is the Sharepoint Site for which the folder/file tree is produced
'
On Error Resume Next
Dim spSite As String, spDir As String, spFile As String, url As String
fnum = FreeFile()
outputFile = "c:\your directory\Tree.txt"
Open outputFile For Output As fnum
Spaces = " "
spSite = "https://your Sharepoint site/"
spDir = ""
spFile = ""
url = spSite & spDir & spFile
Stack.Add (Array(spSite, spDir, spFile, url, "d", 0))
Print #fnum, spSite
Print #fnum, Spaces & spDir
NavigateFolder spSite, spDir, url, 0
Close #fnum
End Sub

Sub NavigateFolder(spSite As String, spDir As String, url As String, level As Integer)
Dim davDir As New ADODB.Record
Dim davFile As New ADODB.Record
Dim davFiles As New ADODB.Recordset
Dim isDir As Boolean
Dim tempURL As String
On Error GoTo showErr
tempURL = "URL=" & url
davDir.Open "", _
tempURL, _
adModeReadWrite, _
adFailIfNotExists, _
adDelayFetchStream ', _
' "username", _
' "password"
If davDir.RecordType = adCollectionRecord Then
Set davFiles = davDir.GetChildren()
Do While Not davFiles.EOF
' davFile.Open davFiles, , adModeReadWrite
davFile.Open davFiles, , adModeRead
isDir = davFile.Fields("RESOURCE_ISCOLLECTION").Value
If Not isDir Then
spFile = Replace(davFile.Fields("RESOURCE_PARSENAME").Value, "%20", " ")
url = spSite & spDir & "/" & spFile
Stack.Add (Array(spSite, spDir, spFile, url, "f", level))
PrintLine = ""
For i = 1 To level + 1
PrintLine = PrintLine & Spaces
Next i
Print #fnum, PrintLine & spFile
Else
level = level + 1
url = Replace(davFile.Fields("RESOURCE_ABSOLUTEPARSENAME").Value, "%20", " ")
spDir = Right(url, Len(url) - Len(spSite))
Stack.Add (Array(spSite, spDir, "", url, "d", level))
PrintLine = ""
For i = 1 To level
PrintLine = PrintLine & Spaces
Next i
Print #fnum, PrintLine & "/" & spDir
NavigateFolder spSite, spDir, url, level
level = level - 1
End If
davFile.Close
davFiles.MoveNext
Loop
End If
Set davFiles = Nothing
davDir.Close
Set davDir = Nothing
' Do something with files here...

GoTo noErr
showErr:
Call MsgBox(Err.Number & ": " & Err.Description & Chr(10) _
& "spSite=" & spSite & Chr(10) _
& "spDir= " & spDir & Chr(10) _
& "spFile=" & spFile, vbOKOnly, "Error")

noErr:
' No errors
End Sub


Sorry about the poor formatting, but I'm not an expert on using this site either.


When I was using Windows XP, this code worked great! I used it all the time. Now I have Windows 7.

When I run it now, I get this error:

===============
-2147217895
Object or data matching the name, range, or selection criteria was not found within the scope of this operation.
===============

It is failing on this line:

davDir.Open "", _
tempURL, _
adModeReadWrite, _
adFailIfNotExists, _
adDelayFetchStream ', _
' "username", _
' "password"


I have searched and searched and can't find anything that pinpoints the problem.


Does anyone know? Thanks.


Dennis
 
Upvote 0
hi,

did u get solution for this issue? if so, please share.

i too face same issue.

Thanks!


Hi. I never did figure this out. Periodically I google this for a solution, but I have yet to find a solution.

The macro I wrote was mostly just for me. I wrote it because it was easier for me to find a file in the mass of folders we have on SharePoint. Would be great to figure this out.
 
Upvote 0

Forum statistics

Threads
1,215,066
Messages
6,122,948
Members
449,095
Latest member
nmaske

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top