Excel's fullname property with OneDrive

后端 未结 12 1974
别那么骄傲
别那么骄傲 2020-12-24 10:12

If I want to use the open Workbook object to get the fullname of an Excel file after saving it, but that file has been synchronized to OneDrive, I get a \"https\" address in

12条回答
  •  遥遥无期
    2020-12-24 10:37

    It's possible to improve on Virtuoso's answer to reduce (though not eliminate) the chance that the function returns a "wrong" file location. The problem is that there are various URLs that a workbook's .FullName can be. These are three I'm aware of:

    1. A URL associated with the user's OneDrive
    2. A URL associated with the user's OneDrive for Business
    3. A URL associated with somebody else's OneDrive in the case that that other person has "shared" the file (in which case you open the file via File > Open > Shared with me)

    On my PC I can get the relevant local folders to map the first two URLs via the OneDriveConsumer and OneDriveCommercial environment variables, that exist in addition to the OneDrive environment variable, so the code below makes use of these. I'm not aware that it's possible to handle the "Shared with Me" files and the code below will return their https://-style location.

    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 - e.g. for "shared with me" files
        End If
    
        Local_Workbook_Name = wb.FullName
    
    End Function
    

    Unfortunately, if files exist with identical paths within both the OneDrive folder and the OneDrive for Business folder, then the code can't distinguish between them, and may return the "wrong one". I don't have a solution for that.

提交回复
热议问题