You can improve Virtuoso’s response to reduce (although not eliminate) the likelihood that the function will return the “wrong” file location. The problem is that there are different URLs, .FullName may be a book .FullName . Here are three that I know of:
- OneDrive User Associated URL
- OneDrive for Business User Associated URL
- The URL associated with someone else on OneDrive, in case this other person has “shared” the file (in this case, you open the file through “File”> “Open”> “Share with me”)
On my PC, I can get the appropriate local folders to map the first two URLs through the OneDriveConsumer and OneDriveCommercial environment variables that exist in addition to the OneDrive environment variable, so the code below uses them. I do not know if it is possible to process the "Shared with Me" files, and the code below will return their location https:// -style.
Private Function Local_Workbook_Name(ByRef wb As Workbook) As String Dim i As Long, j As Long Dim OneDrivePath As String Dim ShortName As String 'Check if it looks like a OneDrive location If InStr(1, wb.FullName, "https://", vbTextCompare) > 0 Then 'Replace forward slashes with back slashes ShortName = Replace(wb.FullName, "/", "\") 'Remove the first four backslashes For i = 1 To 4 ShortName = Mid(ShortName, InStr(ShortName, "\") + 1) Next 'Loop to see if the tentative LocalWorkbookName is the name of a file that actually exists, if so return the name For j = 1 To 3 OneDrivePath = Environ(Choose(j, "OneDrive", "OneDriveCommercial", "OneDriveConsumer")) If Len(OneDrivePath) > 0 Then Local_Workbook_Name = OneDrivePath & "\" & ShortName If Dir(Local_Workbook_Name) <> "" Then Exit Function End If End If Next j 'Possibly raise an error here when attempt to convert to a local file name fails - eg for "shared with me" files End If Local_Workbook_Name = wb.FullName End Function
Unfortunately, if the files exist with the same paths both in the OneDrive folder and in the OneDrive for business folder, the code will not be able to distinguish between them and may return “incorrect”. I have no solution for this.
source share