针对excel 2016的强制合并单元格输入

时间:2017-11-06 07:58:28

标签: excel vba excel-vba

我有一个从D4到H4的合并单元格,我希望单元格是必需的。我曾尝试过以下代码但不起作用。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim c As Range
Dim cel As Range

Set c = Range("D4:H4")

Application.EnableEvents = False
If Not Intersect(Target, c) Is Nothing Then
  For Each cel In c
    If cel.Text = "" Then
      Application.Goto reference:=c, Scroll:=True
      MsgBox ("Field Cannot Be Blank")
      Exit For
    End If
  Next cel
End If
Application.EnableEvents = True
End Sub

我还需要另一个细胞,H2。这段代码已经可以使用了,我想把D4到H4和H2的代码组合在一起。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(2, 8).Value = "" Then
  MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the 
  mandatory cells"
  Cancel = True
End If
End Sub

感谢任何帮助和建议。

1 个答案:

答案 0 :(得分:2)

感谢@Rik Sportel,我试图重新合并细胞并应用elseif声明,现在可以正常使用。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(4, 4).Value = "" Then
  MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
  Cancel = True
ElseIf Cells(2, 8).Value = "" Then
  MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the mandatory cells"
  Cancel = True
End If
End Sub