我有一个范围(合并单元格)M5:O5,需要触发 MsgBox,如下所示:
到目前为止我所拥有的:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim billtoanswer As Integer
'If IsNull(Range("M5:O5")) Then <-- other stuff I was trying
'End
If (Application.Intersect(Range("M5:O5"), Target) Is Nothing) Then
End If
billtoanswer = MsgBox("Use this address for Bill To?", vbYesNo + vbQuestion, "Bill To?")
If billtoanswer = vbYes Then
Range("F26").Value = Range("M4").Value & ", " & Range("M5").Value
End If
End If
End Sub
适用于 Microsoft 365 MSO 的 Microsoft® Excel®(版本 2404 内部版本 16.0.17531.20190)64 位
Private Sub Worksheet_Change(ByVal Target As Range)
Dim billtoanswer As Integer
If (Application.Intersect(Range("M5:O5"), Target) Is Nothing) Then
' Skip
Else
If Trim(CStr(Target.Text)) = "" Then
' Skip
Else
billtoanswer = MsgBox("Use this address for Bill To?", vbYesNo + vbQuestion, "Bill To?")
If billtoanswer = vbYes Then
Range("F26").Value = Range("M4").Value & ", " & Range("M5").Value
End If
End If
End If
End Sub
Application.EnableEvents
If Intersect...
行退出,但在最坏的情况下,如果您愿意,例如当事件代码运行时写入目标单元格 (
M5
),重复触发该事件将使 Excel 崩溃。
目标
Target
变量是对已更改的所有单元格的引用。如果您正在监视单个(目标)单元格的更改,请在代码的延续中使用变量 (
targetCell
),方法是引用它(单个单元格)和
Target
(不必是单个单元格)的交集细胞)。仅当您确保它是单个单元格时才使用
Target
,例如
If Target.Cells.CountLarge = 1 Then
。
工作表模块,例如Sheet1
Private Sub Worksheet_Change(ByVal Target As Range)
ChangeBillingAddress Target
End Sub
标准模块,例如Module1
、
modEvents
...(或同一工作表模块)
Sub ChangeBillingAddress(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Target.Worksheet
Dim targetCell As Range: Set targetCell = ws.Range("M5")
If Intersect(targetCell, Target) Is Nothing Then Exit Sub
If Len(CStr(targetCell.Value)) = 0 Then Exit Sub
Dim BillToAnswer As Long
BillToAnswer = MsgBox("Use this address for Bill To?", _
vbYesNo + vbQuestion, "Bill To?")
If BillToAnswer = vbNo Then Exit Sub
Application.EnableEvents = False ' prevent retriggering the event
ws.Range("F26").Value = CStr(ws.Range("M4").Value) _
& ", " & CStr(targetCell.Value)
Application.EnableEvents = True
End Sub