excel - 检查 Excel 工作表中的空(未填充)记录
问题描述
我有 excel 工作表,我在其中使用了以下 vba 代码来检查空记录:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error GoTo NoBlanks
Dim sh As Worksheet, lastRow As Long, lastCol As Long, emptyCells As Range
Set sh = ActiveSheet 'use here your sheet
lastRow = sh.Range("A" & Rows.Count).End(xlUp).Row
lastCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column
Set emptyCells = sh.Range(sh.Cells(1, 1), sh.Cells(lastRow,
lastCol)).SpecialCells(xlCellTypeBlanks)
If emptyCells.Cells.Count > 0 Then
MsgBox "There are empty cells, which must be filled: " & emptyCells.Address(0, 0)
emptyCells.Select
Else
Resume Next
Exit Sub
End If
NoBlanks:
Resume Next
End Sub
但它仍然让我退出工作表,即使有空记录
有什么方法可以修改此代码 - 因此在记录填充值之前无法关闭我的工作表?
(我在“关闭前”事件中使用了这段代码)
解决方案
请尝试以下代码。我根据您在评论中的要求修改了几行。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim sh As Worksheet, lastRow As Long, lastCol As Long, emptyCells As Range
Set sh = ActiveSheet 'use here your sheet
lastRow = sh.Range("A" & Rows.Count).End(xlUp).Row
'lastRow = sh.UsedRange.Rows.Count
lastCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column
'lastCol = sh.UsedRange.Columns.Count
On Error GoTo NoBlanks
Set emptyCells = sh.Range(sh.Cells(1, 1), sh.Cells(lastRow, _
lastCol)).SpecialCells(xlCellTypeBlanks)
If Not emptyCells Is Nothing Then
MsgBox "There are empty cells, which must be filled: " & emptyCells.Address(0, 0)
emptyCells.Interior.Color = RGB(255, 0, 255)
Cancel = True
Else
NoBlanks:
Cancel = False
sh.Range(sh.Cells(1, 1), sh.Cells(lastRow, _
lastCol)).Interior.ColorIndex = 0
If Me.Saved = False Then Me.Save
'Workbook will be saved & closed if all cells in UsedRange are filled
End If
End Sub
问候。
推荐阅读
- ajax - 使用 ajax 的 Spring 视图页面详细信息
- curl - curl命令替换现有文件夹
- c++ - 如何在 C++ 中将 uint64_t 连接到 unsigned char*?
- java - 如何将文件类型转换为图像?
- react-native - 失败是因为原生 React 运行时不包含 Node 标准库
- javascript - 将两个以上的集合从 firestore 复制到另一个集合不起作用
- javascript - 为什么这个 javascript 代码在输出的最后一行给我 Nan?请问我需要理由
- r - 在 postgres 数据库中使用 R 进行多行和列更新
- typescript - 强制openapi生成器生成一个类
- reactjs - 是否可以通过 useCallback 避免自定义 React Hook 上的“eslint(react-hooks/exhaustive-deps)”错误?