Hey guys, it's been a while. I'm having a real headache with some VBA on a workbook. The goal is to autosave every time a specific button is clicked on a userform:
Private Sub CommandButton1_Click()
Application.EnableEvents = False
'...some other code that I don't think is particularly important to this....
ActiveSheet.Unprotect
ActiveSheet.Cells(ActiveCell.Row, commentsCol) = Me.comments
If Me.permit Then
ActiveSheet.Cells(ActiveCell.Row, permitCol) = "Y"
Else
ActiveSheet.Cells(ActiveCell.Row, permitCol) = ""
End If
ActiveSheet.Cells(ActiveCell.Row, contractorCol) = Me.contractor
ActiveSheet.Cells(ActiveCell.Row, contractorCol + 1) = Now
ActiveSheet.Cells(ActiveCell.Row, contractorCol + 2) = Application.UserName
Application.EnableEvents = True
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
True, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True
Unload Me
ActiveWorkbook.Save '<-----this line fires the workbook_beforesave macro
End Sub
When it reaches the activeworkbook.save line at the end, it fires up the workbook_beforesave command. However, even though the code fires, it doesn't DO anything. I can F8 through the code, and it seems to run, but when it gets to a sht.visible=False line, for instance, nothing happens. Same with thisworkbook.save. It just completely ignores what it's reading. When I click 'Save' manually, the code runs perfectly. Any ideas what might be causing the issue? Am I doing something stupid here?
Workbook_beforesave code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
shtName = ActiveSheet.Name
Application.EnableEvents = False
Application.ScreenUpdating = False
For Each sht In ActiveWorkbook.Sheets
If sht.Name = "Enable macros" Then
sht.Visible = True
Else
sht.Visible = False
End If
Next sht
If SaveAsUI = False Then
ThisWorkbook.Saved = False
ThisWorkbook.Save
Else
Dim bFileSaveAs As Boolean
bFileSaveAs = Application.Dialogs(xlDialogSaveAs).Show
Cancel = True
End If
Cancel = True
For Each sht In ThisWorkbook.Sheets
sht.Visible = True
Next sht
mwarn.Visible = xlSheetVeryHidden
'lists.Visible = xlSheetHidden
Sheets(shtName).Activate
Application.EnableEvents = True
closeyn = False
ThisWorkbook.Saved = True
End Sub
Bookmarks