我在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
答案 0 :(得分:1)
请尝试:
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
“特定工作表的名称”是您验证Cells(5, 2).Value = ""
的工作表名称。
答案 1 :(得分:0)
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
答案 2 :(得分:0)
更直接
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