tl;dr: In the code below, the following two conditions both evaluate to True!!! How? Why?
If Not IsSaved Then
If IsSaved Then
I'm working with the VBA Visual Basic Editor (VBE
) object. The .Saved
property has me baffled.
Both (.Saved)
and Not (.Saved)
return True
if the VBComponent object is in fact saved. I even tried explicitly coercing the property to a Boolean before evaluating the conditional. Here are the steps to reproduce:
- Open a blank workbook in a new instance of Excel
- Copy and run the following code from a standard module (e.g., "Module1"):
Sub ListModules()
Dim VBComp As Object 'VBComponent
For Each VBComp In Application.VBE.ActiveVBProject.VBComponents
Dim IsSaved As Boolean
IsSaved = CBool(VBComp.Saved)
If CStr(VBComp.Saved) = "True" Then
Debug.Print vbNewLine; VBComp.Name; " saved? "; VBComp.Saved; " ("; TypeName(VBComp.Saved); ")"
If Not IsSaved Then
Debug.Print VBComp.Name; " is not saved"
End If
If IsSaved Then
Debug.Print VBComp.Name; " is saved"
End If
End If
Next VBComp
End Sub
'Sample output:
ListModules
ThisWorkbook saved? True (Boolean)
ThisWorkbook is not saved
ThisWorkbook is saved
Sheet1 saved? True (Boolean)
Sheet1 is not saved
Sheet1 is saved
NOTE: To run this code, you may have to grant access to the VBA project object model: File -> Options -> Trust Center -> [Trust Center Settings...] -> Macro Settings -> [x] Trust access to the VBA project object model