在工作簿保存时使特定 sheet 的必填字段
Making fields mandatory of a specific sheet on workbook save
我在 excel 中使用宏来使 excel 工作簿中的字段成为必填项。但是,问题是工作簿包含多个工作表,宏适用于所有工作表。
有没有办法定位工作簿中的特定工作表?
下面是我使用的代码:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Cells(5, 2).Value = "" Then
MsgBox "Please fill cell B5"
Cancel = True
End If
End Sub
请尝试:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name = "Name of specific sheet" Then
If ThisWorkbook.Sheets(i).Cells(5, 2).Value = "" Then
MsgBox "Please fill cell B5"
Cancel = True
End If
End If
Next i
End Sub
其中 "Name of specific sheet" 是您验证 Cells(5, 2).Value = ""
的工作表名称。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim shX As Worksheet
Dim rX As Range
Set shX = ThisWorkbook.Worksheets("Sheet1")
Set rX = shX.Cells(5, 2)
If rX = "" Then
MsgBox "Please fill cell B5"
Cancel = True
shX.Select
rX.Select
End If
End Sub
更直接
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim ws As Worksheet
Set ws = Sheets("Your sheet name here")
If Len(ws.[b5]) = 0 Then
MsgBox "Please fill cell B5 on sheet " & ws.Name, vbCritical, "File not saved"
Cancel = True
Application.Goto ws.[b5]
End If
End Sub
我在 excel 中使用宏来使 excel 工作簿中的字段成为必填项。但是,问题是工作簿包含多个工作表,宏适用于所有工作表。
有没有办法定位工作簿中的特定工作表?
下面是我使用的代码:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Cells(5, 2).Value = "" Then
MsgBox "Please fill cell B5"
Cancel = True
End If
End Sub
请尝试:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name = "Name of specific sheet" Then
If ThisWorkbook.Sheets(i).Cells(5, 2).Value = "" Then
MsgBox "Please fill cell B5"
Cancel = True
End If
End If
Next i
End Sub
其中 "Name of specific sheet" 是您验证 Cells(5, 2).Value = ""
的工作表名称。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim shX As Worksheet
Dim rX As Range
Set shX = ThisWorkbook.Worksheets("Sheet1")
Set rX = shX.Cells(5, 2)
If rX = "" Then
MsgBox "Please fill cell B5"
Cancel = True
shX.Select
rX.Select
End If
End Sub
更直接
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim ws As Worksheet
Set ws = Sheets("Your sheet name here")
If Len(ws.[b5]) = 0 Then
MsgBox "Please fill cell B5 on sheet " & ws.Name, vbCritical, "File not saved"
Cancel = True
Application.Goto ws.[b5]
End If
End Sub