Delete or Overwrite a SharePoint List using Excel VBA? - excel

I am able to add easily create a SharePoint List using Excel VBA with the following code snippet:
ActiveSheet.ListObjects("Table3").Publish Array( _
"http://sitebuilder2.xyzcompany.com/operations", "test1"), False
However, I get an "Run-time error '3003': Application-defined or object-defined error" if I use the same list name ("test1") because the list already exists.
Is there a straight-forward way to either overwrite list ("test1"), or delete list ("test1") in SharePoint using Excel VBA, so that I can update the entire list without providing a new List name?

I was able to synchronize to the SharePoint list using this code.
Private Sub PublishRW()
Dim listPoint As Range
Dim fullServerName As String
Dim retUrl As String
Set listPoint = ActiveCell.ListObject.Range(1, 1)
fullServerName = ServerName.Value & "_vti_bin"
If ListDescription.Value = "" Then
retUrl = ActiveCell.ListObject.Publish(Array(ServerName.Value, ListName.Value), False)
Else
retUrl = ActiveCell.ListObject.Publish(Array(ServerName.Value, ListName.Value, ListDescription.Value), False)
End If
If retUrl <> "" Then
ActiveCell.ListObject.Delete
ActiveSheet.ListObjects.Add xlSrcExternal, Array(fullServerName, ListName.Value), True, xlYes, listPoint
Else
MsgBox "There was an error during publish, please check the server name"
End If
Unload ExportRWList
End Sub

Related

VBA Excel error with Button objects .OnAction

My job we have a lot of reports that's generated. Using a modular approach I'm trying to set up a Excel workbook that dynamically creates sheets based on what report that's picked from Sheet("MainMenu")
Anyways, in the dynamic sheet I have the following
Public Sub OFFD_Report_Parse()
Init 'just declares workbook and worksheet globals
If shtTCL.Visible = False Then shtTCL.Visible = True
shtTCL.Activate
shtMenu.Visible = False
Dim rngBtn1, rngBtn2, rngBtn3, rngBtn4 As Range
Dim btn1, btn2, btn3, btn4 As Button
Set rngBtn1 = shtTCL.Range("B10")
Set btn1 = shtTCL.Buttons.Add(rngBtn1.Left, rngBtn1.Top, rngBtn1.Width, rngBtn1.Height)
With btn1
.OnAction = "TCL1"
.Caption = "Copy 1"
End With
When ran I get Run-time error '1004' Unable to set the OnAction property of the Button Class
The sub it's calling:
Sub TCL1()
Clipboard ("SELECT ORDER WITH FLAG.DELETE = " & Chr(34) & "Y" & Chr(34) & Chr(13))
CopyMsg
End Sub
Is in the same module. I've used this exact method of code in another excel file with no issues which is really making me stumped.
Thank you in advance!!!!
There are two things you need to do to solve your problem.
The code must be in a standard module, not the sheet-behind
You can't have a numeric suffix on the action
I also notice that you're trying to dim a bunch of variables instead of using an array or collection. Only dim one variable per line. Each variable needs the As statement. Those that are omitted are declared as a variant by default.
If you use a collection you can dynamically generate the array without knowing how many elements it will have up front.
Where I explicitly call out the index of the collection (0) you could instead use a loop and a loop counter.
EXAMPLE:
Option Explicit
Public Sub OFFDReportParse()
Init 'just declares workbook and worksheet globals
If shtTCL.Visible = False Then shtTCL.Visible = True
shtTCL.Activate
shtMenu.Visible = False
Dim buttonRanges As Collection
Dim newButtons As Collection
buttonRanges.Add shtTCL.Range("B10")
newButtons.Add shtTCL.Buttons.Add(buttonRanges(0).Left, buttonRanges(0).Top, buttonRanges(0).Width, buttonRanges(0).Height)
With newButtons(0)
.OnAction = "TCLaction"
.Caption = "Copy 1"
End With
End Sub
Public Sub TCLaction()
Clipboard ("SELECT ORDER WITH FLAG.DELETE = " & Chr(34) & "Y" & Chr(34) & Chr(13))
CopyMsg
End Sub

Why am I recieving the error message "Runtime Error '91'" abd How can I fix this?

I am new to VBA and Macros, this is my first attempt to code. So... I have a word document that functions as a template for report generation. The word document has tables/charts linked to an excel document. I am trying to create a macro that will take the existing source linked in the word document and change/Update them to the new desired location. The idea is to have the user run the macro and then be prompted to choose an excel file and the macro will automatically update all of the tables and charts.
I am receiving a
" Run-time error '91': Object variable or With block variable not set"
message for the following line:
ActiveDocument.Fields(x).LinkFormat.SourceFullName = newFile
After doing some research, I believe the problem is that I am assigning an object variable to a value. Which instead needs to be "set" due to it being an object? Therefore, I have tried changing the line to the following
Set ActiveDocument.Fields(x).LinkFormat.SourceFullName = newFile
which in return gets a
"Compile error: Invalid use of property"
message on the .SourceFullName part of the code.
As previously mentioned, I am a complete newbie and am effectively lost at this point. Any advice and pointers will be welcomed. I have palns in the future to automate other aspects of the report but this is the main time-consumer of the report process and is the reason as to why I am starting with this.
Thanks Guys!
Sub changeSource()
Dim dlgSelectFile As FileDialog 'FileDialog object '
Dim thisField As Field
Dim selectedFile As Variant
Dim newFile As Variant
Dim fieldCount As Integer '
Dim x As Integer
Set dlgSelectFile = Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
With dlgSelectFile
.Filters.Clear 'clear filters
.Filters.Add "Microsoft Excel Files", "*.xls, *.xlsb, *.xlsm, *.xlsx" 'filter for only Excel files
'use Show method to display File Picker dialog box and return user's action
If .Show = -1 Then
For Each selectedFile In .SelectedItems
newFile = selectedFile 'gets new filepath
Next selectedFile
Else 'user clicked cancel
Exit Sub
End If
End With
Set dlgSelectFile = Nothing
'update fields
fieldCount = ActiveDocument.Fields.Count
For x = 1 To fieldCount
ActiveDocument.Fields(x).LinkFormat.SourceFullName = newFile
Next x
MsgBox "Source data has been successfully imported."
End Sub

SharePoint Checkin file - Method or data member not found

When running the below VBA script, macro checkin, I am getting the error 'Method or Data Member Not Found. Can someone please help identify the issue?
Sub checkin()
Dim docCheckIn As String
docCheckIn = "File Location and Name"
Call UseCheckIn(docCheckIn)
End Sub
Sub UseCheckIn(docCheckIn As String)
docCheckIn = "File Location and Name"
' Determine if workbook can be checked in.
If Workbooks.CanCheckIn(docCheckIn) = True Then
Workbooks.checkin docCheckIn
Else
MsgBox "Unable to check in this document at this time."
End If
End Sub
Looks like Workbooks.CanCheckIn(docCheckIn) = True is the problem. What are you trying to achieve? What's CanCheckIn meant to be?
/edit:
Workbooks(docCheckIn).CanCheckIn will work but the docCheckIn must be a workbook name, not full path. Alternatively set the workbook as object using your docCheckIn path and use WbObj.CanCheckIn
/edit2:
bear in mind that the Workbooks.checkin docCheckIn will have to be changed the same way to either Workbooks("workbookname.xls").checkin or WbObj.checkin
To set workbook object:
Set WbObj = Workbooks("workbookname.xls") 'if it's open
Set WbObj = Workbooks.Open(docCheckIn) 'if it isn't open

How do I reference a Cell value stored in an excel file on sharepoint in VBA

For the purpose of version control for my file, I want to be able to run a script that compares Cell A1 on Sheet VC, to the same cell/sheet of a version stored on Sharepoint when I run my script. Fairly new to using VBA and cant work out how to do it and cant find the answer im looking for on google.
The code I want to use:
Public Sub version_control()
Sheets("VC").Calculate
If Sheets("VC").Range("A1").Value <> (this is where I want it to check cell A1 sheet VC on the Sharepoint file)
MsgBox "Please download the latest version from the Sharepoint"
Application.Quit
End If
End Sub
Guessing, you don't already have the SharePoint file open ... if that's true skip down.
But if it's open you can reference it like any other open workbook ... e.g. both of these should work:
debug.Print Workbooks("MySharePointWorkbook.xlsx").Sheets("VC").Range("A1").Value
debug.Print Workbooks.Item(n).Sheets("VC").Range("A1").Value
Probably not already open right? Without getting into the weeds of external data links, I would just obtain the full URL of the SharePoint file (open it, ? Activeworkbook.FullName in the Immediate Window) and store that string in serverFileName like this:
Public Sub version_control()
Dim serverFileName As String 'obtain url for sharepoint filename, insert below
Dim valuesAreDifferent As Boolean 'so we can do housekeeping below
Dim x As New Excel.Application 'make a new session for the sharepoint version
Dim w As Workbook 'grab-handle for the sharepoint file
Sheets("VC").Calculate
valuesAreDifferent = False 'implicit, being explicit
serverFileName = "http://whatever-domain.com/MySharepointWorkbook.xlsx"
x.Visible = False 'so it doesn't flash up when checking
Set w = x.Workbooks.Open(serverFileName) 'open the sharepoint version
If Sheets("VC").Range("A1").Value <> w.Sheets("VC").Range("A1").Value Then _
valuesAreDifferent = True
'housekeeping in case we don't quit
w.Close
x.Quit
Set w = Nothing
Set x = Nothing
If valuesAreDifferent Then
MsgBox "Please download the latest version from the Sharepoint"
Application.Quit
End If
End Sub

VBA Run-time error 1004: Method Range of object _Global failed when trying to create tables in Excel 2013

I understand similar questions with these errors have been posted before, but I found nothing when it came to formatting tables so don't close this please. In my VBA code in MS Access 2013 it exports data from MS Access to Excel. 6 different queries get exported into 1 excel file, each on a different worksheet. This works fine. I then format each sheet to have all the data in a table. I have a form which lets the user choose the path to save the file. If it is the first time creating the file, it works properly. If it is the second time creating the file in that same directory, it doesn't work and it gives me the error:
Run-time error 1004: Method Range of object _Global failed
I figured this was because I was overwriting my file instead of deleting it and recreating it. So I added in some code to check if the file exists, and if it does, delete it. I added breakpoints and while running through this part of the code, I was watching my documents folder. The file successfully got deleted and then recreated which is what I wanted. It still gave me that error. I manually went to delete the file and then reran my code again. It worked properly.
How come I need to manually delete this file in order to rerun my code? Or is it something else that is causing the problem? Here is the important parts of my code as the whole thing is too long to post:
'Checks if a file exists, then checks if it is open
Private Sub checkFile(path As String)
Dim openCheck As Boolean
'If file exists, make sure it isn't open. If it doesn't, create it
If Dir(path) <> "" Then
openCheck = IsFileLocked(path)
If openCheck = True Then
MsgBox "Please close the file in " & path & " first and try again."
End
Else
deleteFile (path)
End If
Else
End If
End Sub
Sub deleteFile(ByVal FileToDelete As String)
SetAttr FileToDelete, vbNormal
Kill FileToDelete
End Sub
Private Sub dumpButton_Click()
On Error GoTo PROC_ERR
Dim path As String
Dim testBool As Boolean
path = pathLabel4.Caption
path = path & Format(Date, "yyyy-mm-dd") & ".xlsx"
checkFile (path)
dumpQueries (path)
formatFile (path)
'Error Handling
PROC_ERR:
If Err.Number = 2001 Then
MsgBox "A file may have been sent to " & path
Exit Sub
ElseIf Err.Number = 2501 Then
MsgBox "A file may have been sent to " & path
Exit Sub
ElseIf Err.Number = 3021 Then
MsgBox "A file may have been sent to " & path
Exit Sub
ElseIf Err.Number = 2302 Then
MsgBox "A file may have been sent to " & path
Exit Sub
ElseIf Err.Number = 0 Then
MsgBox "Your file has been stored in " & pathLabel4.Caption
Exit Sub
Else
MsgBox Err.Number & ": " & Err.Description & vbCrLf & vbCrLf & "New Error. Please contact the IT department."
End If
Private Sub dumpQueries(path As String)
Dim obj As AccessObject, dB As Object
Set dB = Application.CurrentData
For Each obj In dB.AllQueries
testBool = InStr(obj.name, "Sys")
If testBool <> True Then
If obj.name = "example1" Or obj.name = "example2" Then
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, obj.name, path, True, editWorksheetName(obj.name)
End If
End If
Next obj
End Sub
'Autofits the cells in every worksheet
Private Sub formatFile(path As String)
Dim Date1 As Date, strReportAddress As String
Dim objActiveWkb As Object, appExcel As Object
Set appExcel = CreateObject("Excel.Application")
appExcel.Visible = False
appExcel.Application.Workbooks.Open (path)
Set objActiveWkb = appExcel.Application.ActiveWorkbook
With objActiveWkb
Dim i As Integer
For i = 1 To .Worksheets.count
.Worksheets(i).Select
.Worksheets(i).Cells.EntireColumn.AutoFit
.Worksheets(i).ListObjects.Add(xlSrcRange, Range("A1").CurrentRegion, , xlYes).name = "myTable1"
Next
End With
appExcel.ActiveWindow.TabRatio = 0.7
objActiveWkb.Close savechanges:=True
appExcel.Application.Quit
Set objActiveWkb = Nothing: Set appExcel = Nothing
End Sub
The error occurs near the bottom of the code. It's the line:
.Worksheets(i).ListObjects.Add(xlSrcRange, Range("A1").CurrentRegion, , xlYes).name = "myTable1"
There may be a couple functions I left out but they work fine and shouldn't be needed for answering the question.
This is the only relevant code:
Set objActiveWkb = appExcel.Application.ActiveWorkbook
With objActiveWkb
Dim i As Integer
For i = 1 To .Worksheets.count
.Worksheets(i).Select
.Worksheets(i).Cells.EntireColumn.AutoFit
.Worksheets(i).ListObjects.Add(xlSrcRange, Range("A1").CurrentRegion, , xlYes).name = "myTable1"
Next
End With
Things get easier to follow when you trim the fluff away and start naming things - there's no need to .Select anything, appExcel is already an Application object, and there's no need to make a copy reference to the active workbook just to use in a With block, especially if that copy is going to be an Object variable anyway - if the copy were a Workbook object then you would at least get IntelliSense for its members...
Your source range is ambiguous. Range("A1") in Excel-VBA is an implicit reference to the active worksheet.. but this is Access-VBA, so there's no such thing, xlSrcRange is an enum value defined in the Excel object model, so if you don't have a reference to the Excel object model (you're late-binding this, right?), and Option Explicit isn't specified, then xlSrcRange is treated by VBA like just another undeclared/uninitialized variable, and therefore you're passing a 0 there, and the xlSrcRange enum value stands for a 1 - and 0 happens to be the underlying value for xlSrcExternal. Same with xlYes.
Since we cannot possibly guess what the actual source range is supposed to be from the code you posted, I'm leaving you with this:
Dim target As Object
Dim srcRange As Object
Set srcRange = TODO
With appExcel.ActiveWorkbook
Dim i As Integer
For i = 1 To .Worksheets.Count
.Worksheets(i).Cells.EntireColumn.AutoFit
Set target = .Worksheets(i).ListObjects.Add(1, srcRange, , 1)
If target Is Not Nothing Then target.Name = "myTable1"
Next
End With
Side question... why name the table myTable1 when Excel will already have named it Table1 anyway? Also note, if .Add fails, your code blows up with a runtime error 91 because you'd be calling .Add off Nothing. Verifying that the target is not Nothing before setting its Name will avoid that.
To answer your question in the comments:
#Mat'sMug is this what you were talking about? because it gives me this error: "438: Object doesn't support this property or method" Here's the code: .Worksheets(i).ListObjects.Add(SourceType:=xlSrcRange, Source:=.Cells(1).CurrentRegion, _ XlListObjectHasHeaders:=xlYes, TableStylename:="TableStyleMedium1").name = "Table"
The reason this throws a 438 is because your With block variable is a Workbook object, and a Workbook object doesn't have a .Range member.
What I was talking about, is that in Excel VBA unqualified calls to Range, Row, Column, and Cells are implicitly referencing the ActiveSheet, and unqualified calls to Worksheets, Sheets and Names are implicitly referencing the ActiveWorkbook - that's a recurrent problem in a lot of VBA code and a very common mistake to make. The solution is basically to say what you mean, and mean what you say; in this case the failure is on "mean what you say" - the unqualified Range("A1") call is, according to the error message, calling [_Globals].Range("A1")... which is weird because it implies that you're referencing the Excel object model library, which means your late-binding and Object variables could just as well be early-bound: why deal with Object variables and lack of IntelliSense when you're already referencing the library you're late-binding to?

Resources