问题
Simply put, I want to make an Excel form that requires the user to fill in 5 cells, if even one isnt filled in then they cannot save the file. The issue is that with my current implementation I cant even save the blank document to be distributed to my coworkers. Is there a way to save once here and THEN have my VBA script work? below I have the code I've made for the form:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim whatCell As String
whatCell = "B3"
If Sheets("Report").Range(whatCell).Value = "" Then
MsgBox "Pls enter value in Submitter"
Cancel = True 'cancels the save event
Exit Sub
End If
whatCell = "B4"
If Sheets("Sheet1").Range(whatCell).Value = "" Then
MsgBox "Pls enter value in Time/Date"
Cancel = True 'cancels the save event
Exit Sub
End If
whatCell = "B5"
If Sheets("Sheet1").Range(whatCell).Value = "" Then
MsgBox "Pls enter value in Customer Info"
Cancel = True 'cancels the save event
Exit Sub
End If
whatCell = "B6"
If Sheets("Sheet1").Range(whatCell).Value = "" Then
MsgBox "Pls enter value in Issue Description"
Cancel = True 'cancels the save event
Exit Sub
End If
whatCell = "B7"
If Sheets("Sheet1").Range(whatCell).Value = "" Then
MsgBox "Pls enter value in Repeatable"
Cancel = True 'cancels the save event
Exit Sub
End If
End Sub
Private Sub Workbook_Open()
End Sub
回答1:
Find an empty cell (let's say A1) and put a value in it. Your BeforeSave code checks to see if that cell's populated, and skips the checks if it is. Before exiting it clears the cell.
Option Explicit
Dim msg As String
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
msg = ""
If Sheets("Sheet1").Range("A1").Value <> "" Then
Sheets("Sheet1").Range("A1").Value = ""
Exit Sub
End If
EmptyCell Sheets("Report").Range("B3"), "Submitter"
EmptyCell Sheets("Sheet1").Range("B4"), "Time/Date"
EmptyCell Sheets("Sheet1").Range("B5"), "Customer Info"
EmptyCell Sheets("Sheet1").Range("B6"), "Issue Description"
EmptyCell Sheets("Sheet1").Range("B7"), "Repeatable"
If Len(msg) > 0 Then
MsgBox "The following values are required before saving:" & _
vbLf & msg, vbExclamation
Cancel = True
End If
End Sub
Sub EmptyCell(rng As Range, msgErr As String)
If rng.Value = "" Then msg = msg & vbLf & msgErr & _
" (" & rng.Parent.Name & "," & rng.Address(False, False) & ")"
End Sub
来源:https://stackoverflow.com/questions/31861063/excel-make-a-field-required-before-saving-but-let-me-save-the-blank-form