我正在使用“SHEET1”和“SHEET2”编写工作簿。现在,当SHEET1或SHEET2中有一个空单元格时,它将提示用户在必填单元格上添加值。
Example:
CELL B2 = NULL in SHEET1
- It will prompt the user that there's a missing value on that cell and redirect to that cell but once the you clicked the message box, it will redirect to the SHEET2.
问题:如果丢失的单元格用于SHEET1,我不想激活SHEET2。
以下是我的代码:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim maxrow As Long
Dim maxrow2 As Long
Dim errcnt As Long
Dim errcnt2 As Long
ThisWorkbook.Sheets("SHEET1").Select
ThisWorkbook.Sheets("SHEET1").Cells(1, 1).Select
Range("A1048576").Select
Selection.End(xlUp).Select
maxrow = Selection.Row
For I = 2 To maxrow
If ThisWorkbook.Sheets("SHEET1").Cells(I, 1).Value = "YES" Then
For j = 2 To 10
If ThisWorkbook.Sheets("SHEET1").Cells(I, j).Value = "" Then
ThisWorkbook.Sheets("SHEET1").Select
ThisWorkbook.Sheets("SHEET1").Cells(I, j).Activate
errcnt = errcnt + 1
End If
Next j
End If
If ThisWorkbook.Sheets("SHEET1").Cells(I, 1).Value = "NO" Then
For j = 2 To 10
If ThisWorkbook.Sheets("SHEET1").Cells(I, j).Value = "" Then
ThisWorkbook.Sheets("SHEET1").Select
ThisWorkbook.Sheets("SHEET1").Cells(I, j).Activate
errcnt = errcnt + 1
End If
Next j
End If
Next I
If errcnt > 0 Then
MsgBox "There are " & errcnt & " fields missing", vbExclamation, "Missing Value"
Cancel = True
Else
End If
ThisWorkbook.Sheets("SHEET2").Select
ThisWorkbook.Sheets("SHEET2").Cells(1, 1).Select
Range("A1048576").Select
Selection.End(xlUp).Select
maxrow2 = Selection.Row
For X = 2 To maxrow2
If ThisWorkbook.Sheets("SHEET2").Cells(X, 1).Value = "YES" Or ThisWorkbook.Sheets("SHEET2").Cells(X, 1).Value = "NO" Then
For j = 2 To 10
If ThisWorkbook.Sheets("SHEET2").Cells(X, j).Value = "" Then
ThisWorkbook.Sheets("SHEET2").Select
ThisWorkbook.Sheets("SHEET2").Cells(X, j).Activate
errcnt2 = errcnt2 + 1
End If
Next j
End If
Next X
If errcnt2 > 0 Then
MsgBox "There are " & errcnt & " fields missing", vbExclamation, "Missing Value"
Cancel = True
Else
End If
End Sub
我相信这是因为这段代码:
ThisWorkbook.Sheets( “SHEET2”)。选择
答案 0 :(得分:0)
而不是:
If errcnt > 0 Then
MsgBox "There are " & errcnt & " fields missing", vbExclamation, "Missing Value"
Cancel = True
Else
End If
试试这个:
If errcnt > 0 Then
MsgBox "There are " & errcnt & " fields missing", vbExclamation, "Missing Value"
Cancel = True
Exit Sub
End If
注意我通过exit sub更改了ELSE(那里没用)。如果SHEET1中缺少某些内容,则会触发结束宏,并且不会继续选择SHEET2。