Determine if an Excel workbook has ever been saved?

前端 未结 3 1882
迷失自我
迷失自我 2021-01-04 13:45

How can I tell, using VBA, if an Excel workbook has ever been saved?

I want to know if clicking save will save the document to an existing location or prompt me to c

相关标签:
3条回答
  • 2021-01-04 13:53

    I found this helpful. .BuiltinDocumentProperties("last save time") returns a vbDate (VarType = 7) representing the last time the workbook was saved ONLY IF the file has been saved at least once. Otherwise it returns a vbObject (VarType = 9).

    Function WbSavedAtLeastOnce(ByVal target As Workbook) As Boolean
    ' Returns TRUE if the target workbook has been saved at least once.
    
        ' .BuiltinDocumentProperties("last save time") returns a vbDate
        '   only if the file has been saved at least once.
        WbSavedAtLeastOnce = VarType( _
                target.BuiltinDocumentProperties("last save time")) = 7
    End Function
    

    Use the function like this:

    Sub Test()
        Dim wb As Workbook
        Set wb = ActiveWorkbook
    
        If WasSavedAtLeastOnce(wb) = True Then
            MsgBox "This file has been saved at least once."
        Else
            MsgBox "This file has never been saved."
        End If
    End Sub
    
    0 讨论(0)
  • 2021-01-04 13:56
    If ActiveWorkbook.Path = vbNullString Then
        'actions if the active workbook hasn't been saved yet go here
    Else
        '....
    End If
    
    0 讨论(0)
  • 2021-01-04 14:06

    The name (e.g. Book1) is a clue although I suppose someon could simply save their workbook with that name.

    A clearer check may be as simple as a worksheet function that only works on a saved workbook.

    'the following returns an empty string if used on an unsaved workbook
    =CELL("filename", A1)
    

    In VBA the .Address property will return no path when used with the External:=True argument.

    ?range("A1").Address(external:=true)
    [Book1]Sheet5!$A$1
    
    0 讨论(0)
提交回复
热议问题