Unintended file dialog when updating links in Excel 2003 VBA - excel

I'm keeping sets of interrelated Excel 2003 spreadsheets for each of my company's projects.
I want to copy some template XLS files to the project name and change the links that connect them to each other.
For example, the file TEMPLATE_ScanProgress.xls links to TEMPLATE_Film_Review.xls.
I am copying them both to 123456_ScanProgress.xls and 123456_Film_Review.xls, and updating the link in 123456_ScanProgress.xls.
Sample code of what I'm doing:
If Dir("WorkOrder & "_ScanProgress.xls") = "" Then
FileCopy "TEMPLATE_ScanProgress.xls", WorkOrder & "_ScanProgress.xls"
Workbooks.Open Filename:=WorkOrder & "_ScanProgress.xls", UpdateLinks:=0
ActiveWorkbook.ChangeLink "TEMPLATE_Film_Review.xls", _
WorkOrder & "_Film_Review.xls", _
xlLinkTypeExcelLinks
Workbooks(WorkOrder & "_ScanProgress.xls").Close SaveChanges:=True
Else
FileExists = True
FileExistsWarning_7 = WorkOrder & "_ScanProgress.xls"
End If
The problem is that when the code tries to update the link I get a file dialog asking me to choose a file for the change, even though I already specified which file I want in the code.

Try setting DisplayAlerts to False. DisplayAlerts is on the Application object and is used to suppress dialog boxes for example when overwriting a file. It may work in this case too.

Related

Sharepoint Locking Error when xlsm is Uploaded via VBA .SaveAs

This VBA macro takes a template xlsm file saved on a shared drive and automatically uploads the file saved as with tomorrow's date in the title to SharePoint. It is triggered by a specific appointment reminder out of Outlook.
Although the file is saved to the SharePoint library, it seems to be locked for any kind of editing.
Error when trying to edit the file in browser:
Can't Lock File for Editing
Close
Error
We're sorry. We couldn't lock this file for editing. Would you like to try again?
Error when trying to edit properties in browser:
The file "http://sharepoint/TESTING FILE.xlsm" is locked for exclusive use by i:0#.w|"MyuserID".
Sub savetest()
Dim Template As Workbook
Workbooks.Open ("C:\MyFilePath\Name")
Set Template = Workbooks("Name.xlsm")
Template.SaveAs FileName:= _
"http://sharepoint/MyLibrary/MyFilePath/Name" &
Format(WorksheetFunction.WorkDay(Date, 1), "MM-DD-
YYYY") & ".xlsm?web=1" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled,
CreateBackup:=False
End Sub

How to deal with co-authoring while editing an Excel file in Sharepoint via VBA

I have an excel file stored in Sharepoint (which is also accessible with Microsoft Teams), with the path: https://organization.sharepoint.com/PathOfFile/myFile.xlsx
The file can be edited by multiple at the same time with the co-authoring feature in Sharepoint.
I want to use another excel file stored locally in my computer to access and modify the one in Sharepoint. This local file has a button with this VBA code in it:
Sub UpdateSP():
f_name = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
Workbooks.Open f_name
Workbooks("myFile.xlsx").Activate
ActiveWorkbook.Sheets("sheet1").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Value = 9999
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = 0000
ActiveWorkbook.Close SaveChanges:=True
End Sub
In principle it works, the file in Sharepoint is modified. But things go wrong if there's someone editing the file while I run the code, then two versions of the file seem to be created, one for the online-live editing, and the one for my code.
If this happens, the online version of the file won't show the changes made by the code, and whenever the file is opened with the excel app, a pop-up will show asking which version of the file should be kept, losing all the changes done in the disposed version.
I have tried to use the CanCheckOut and CheckOut methods, but CanCheckOut always returns False for whatever reason (there are some questions here with the same issue but I havent been able to find a solution).
Can someone suggest a solution to this issue? Thanks.
I'm not 100% sure it will work on SharePoint, but in theory, ADODB is a library for VBA that has the syntax of objects to use Microsoft's Jet Engine so you can open files AdLockOptimistic---ally. ((look up lock types in ADO.net))
This works on a file directory basis, so if the DB being modified is open, it will handle the update.
Instead of using Excel's Application to open the file, you would establish an ADO connection, and then specify the type of Lock in order to access the Excel's sheets and tables inside it.
This works for shared / network drives, so I'm guessing since SharePoint can be mapped as a file explorer drive, then ADO should work and is worth a try.
Here's a basic example to get you started: ADO question
Try enabling the autosave after activating the workbook.
To do so, add this line:
ActiveWorkbook.AutoSaveOn = True
after the Workbooks("myFile.xlsx").Activate line.
I have had similar issues with collaborative files and making sure the autosave is enabled has solved it.
To be able to incorporate changes that way your code must run inside a coauthoring context.
Instead of opening the document from another doc or local copy, the code must be running inside the same document being opened from the same source URL (Sharepoint or OneDrive), that way the add-in or macro can make changes that Excel itself will handle on a coauthoring context.
I recommend taking a look at Coauthoring in Excel add-ins of the Office Dev Center, including the linked articles inside (specifically "coauthoring", redirecting to the support center, and "About coauthoring in Excel (VBA)" at the bottom with more samples).
CanCheckOut will always return false if a workbook is open. Thus you must check before you touch it. The CheckOut command will not open the file so we must also have an open statement after CheckOut.
Using your example it would look like this;
Option Explicit
Public Sub UpdateSP()
Dim fName As String
fName = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
If Workbooks.CanCheckOut(fName) Then
Workbooks.CheckOut fName
Dim myFile As Workbook
Set myFile = Workbooks.Open(fName)
Dim mySheet As Worksheet
Set mySheet = myFile.Sheets("Sheet1")
Dim startRange As Range
Set startRange = mySheet.Range("A" & mySheet.Rows.Count).End(xlUp).Offset(1)
startRange.Value = 9999
startRange.Offset(0, 1).Value = 0
myFile.Close SaveChanges:=True
Else
MsgBox fName & " can't be checked out at this time.", vbInformation
End If
End Sub

Cannot save file to Sharepoint Online using VBA (Permissions error)

This is one of my first times using VBA. I have a command button that is supposed to be saving a file as, to my sharepoint online documents page. I can use the "excel services" and save to that documents page from excel manually, but when i try the same in VBA it is saying I do not have permission. Below is the code I am using, any advice would be much appreciated!
Private Sub CommandButton1_Click()
Dim path as string
dim filename1 as string
path = "https://xxxxxx.sharepoint.com/sites/xxxxx/Shared Documents"
filename1 = Range("B3").text
activeworkbook.SaveAs FileName:=path & filename1 & ".xlsx", _
FileFormat:=xlopenxmlworkbook
End Sub
If your current file is in the same folder as the destination you would like to save in, try this change for the definition of path:
path = "https://xxxxxx.sharepoint.com/sites/xxxxx/Shared Documents/"
The missing final / in your code is causing the FileName argument to be invalid, because path & filename1 & ".xlsx" evaluates to
https://xxxxxx.sharepoint.com/sites/xxxxx/Shared Documents[filename1].xlsx
Which means if permissions weren't restricted on the /xxxxx folder you would have written a badly named Excel workbook in that location.
ALTERNATIVE SOLUTION
Potentially another solution for your problem. Save an empty workbook in the location you wish to save your new Excel files. Open the empty Excel file, and run your macro there. Change the path line to:
path = ActiveWorkbook.Path & "\"
Try this to see if it works instead. This is how I got around Sharepoint permissions problems.

Excel VBA: Automated Excel Backup Stopped Working due to "Compile Error: Cannot find file or library"

I have an inventory xls file, that includes a diagram of the office. When the xls is opened, the VBA automatically makes a backup of the file before any changes are made. That has worked for the past year. Today it has broken.
Yesterday, the file was working fine.
1) I added some info to the xls sheet - nothing unusual; the same sort of info I've added over the past year. I did NOT edit the VBA.
2) I added some objects (shapes-circle, square, etc) to the tab with the office diagram.
Today, the file is not working.
1) The VBA debugger gives an error on open: "Compile Error: Cannot find file or library."
2) Numerous text boxes/shapes have vanished off the tab with the diagram. I did not remove them.
UPDATE 1: I moved a shape on the diagram, and all the text boxes reappeared.
Any suggestions to fix this are appreciated.
'Saves an exact copy of the file upon opening it to the \Back_Tracker location and added today's date to the filename.
Private Sub Workbook_Open()
Dim WBPath As String, WBName As String, TimeStampStr As String, PassW As String
WBPath = ThisWorkbook.Path
WBName = ThisWorkbook.Name
'PassW = "something"
Const cstrBACKUP As String = "Backup_Tracker"
If InStr(1, WBPath, cstrBACKUP) = 0 Then 'prevent backups from making backups of themselves.
TimeStampStr = Format(Now(), "YYYY-MM-DD_hh-mm_")
'Application.StatusBar = "Saving backup..."
ActiveWorkbook.SaveCopyAs Filename:=WBPath & Application.PathSeparator & cstrBACKUP & Application.PathSeparator & TimeStampStr & WBName
'Application.DisplayStatusBar = False
'Application.DisplayStatusBar = True
End If
End Sub
My experience with Excel VBA is that the code can sometimes corrupt when opening. It used to be the case with Access as well, but I'm not sure if that was eventually fixed.
My solution was to either make backup copies after each edit, or use source control for the Excel file. Its the only way to be sure.
Found the problem.
Unchecked this, and it's working now.
Reference
Open the database or application.
Open a module in Design view or press ALT+F11 to switch to the Visual Basic Editor.
On the Tools menu, click References.
Clear the check box for the type library or object library marked as "Missing:"

ExecuteExcel4Macro & update values dialog box

I'm currently coding a small VBA tool in order to quickly sort files according to some data inside. As an example, I have a "To be sorted" folder with some files in it, lets say "File1.xls, File2.xls" and so on.
To read data in "FileX.xls", I use ExecuteExcel4Macro (with the range and filename set properly), then I can use this data to apply filters and move files in other directories.
My code works fine with local files, but when I try to run it on my server (the tool aims at sorting files stored on the server), a dialog box "Update values" appears when I use ExecuteExcel4Macro.
From here, I have to options:
manually opening each file before running the macro (I have like 250 files to sort so...)
pressing cancel on the dialog box which causes the plugin to crash (type mismatch error)
Here is the portion of code that bothers me
For Each fsoFile In fsoParentFol.Files
'I only want to sort .xls files
If Right(fsoFile.Name, 4) = ".xls" Then
'On active le workbook actuel
strRef = "'[" & fsoFile.Name & "]" & "Sheet1" & "'!"
'this is the data I want to retrieve ... and this is where the dialog pops up
projectName = ExecuteExcel4Macro(strRef & rngProjectName.Address(1, 1, xlR1C1))
'some more code goes here but is irrelevant
End If
Next fsoFile
So my question is: how can I disable this dialog or, if it's a bad idea, are there other clean methods (I don't want to open each workbook, even with screenupdate turned off) that could solve my issue?
DisplayAlerts = False doesn't solve the problem. And again, the program runs fine without this dialog.
I've of course tried to research online my problem first before posting here, but even subjects like this one aren't solutions to my problem.
Change the UNC path to a path using the drive letter that the server is mapped to:
So for example, change your string to produce:
[P:\Some_Folder\myfile.xls]Sheet1!A1
Instead of:
[\\my-server\Some_Folder\myfile.xls]Sheet1!A1
You could try using the replace function to achieve this:
strRef = "'[" & Replace(fsoFile.Name, "\\", "P:\") & "]" & "Sheet1" & "'!"
I would use code more like this:
projectName = Workbooks.Open("\\srv1\folder\Book1.xlsx").Sheets("Sheet1").Range("a1")
Workbooks("Book1.xlsx").Close
This works with a mapped network drive too.

Resources