如果列(C)中的单元格已填满,我有一个问题是要强制填充5列(E I J L M)。
我已经编写了这段代码,但我确实无法将C列链接到:(
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long, lngTCols As Long
Dim lngRowCheck(1 To 5) As String
lngRowCheck(1) = "E"
lngRowCheck(2) = "I"
lngRowCheck(3) = "J"
lngRowCheck(4) = "L"
lngRowCheck(5) = "M"
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To UBound(lngRowCheck)
For Each rngCell In Range(lngRowCheck(i) & "2:" & lngRowCheck(i) & lngLstRow)
If rngCell.Value = "" Then
MsgBox ("Please enter an input in cell " & rngCell.Address)
rngCell.Select
End If
Next
Next i
End Sub
答案 0 :(得分:1)
在循环进入列之前,您需要检查C列是否为空。
以下代码正在执行您之后的操作,但为什么仅在保存之前检查工作簿?如果这些列对于该特定工作表是疯狂的,则应使用工作表事件( Worksheet_Activate , Worksheet_SelectionChange ),跟踪当前选定的行以及何时选择更改行,检查列C等。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long, lngRow As Long
Dim arrColsToCheck As Variant, oItem As Variant
arrColsToCheck = Array("E", "I", "J", "L", "M")
With ActiveSheet ' Only 1 sheet in workbook?
lngLstRow = .UsedRange.SpecialCells(xlLastCell).Row
For lngRow = 1 To lngLstRow
' Check if column C is filled (not empty)
If Not IsEmpty(.Cells(lngRow, "C")) Then
' Check the mandatory columns
For Each oItem In arrColsToCheck
Set rngCell = .Cells(lngRow, oItem)
If IsEmpty(rngCell) Then
rngCell.Select
MsgBox ("Please enter an input in cell " & rngCell.Address(0, 0))
End If
Set rngCell = Nothing
Next
End If
Next lngRow
End With
End Sub
对于需要此检查的工作表上的代码:
Option Explicit
Private ActiveRow As Long
Private Sub Worksheet_Activate()
ActiveRow = ActiveCell.row
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.row <> ActiveRow Then
' Call the Column C check for Madatory fields, passing the ActiveRow to it
' You implement this Sub with a "Long" as argument
End If
End Sub