我正在尝试运行一个宏来填充更新内容的日期和时间,但我需要在同一行中进行两次。
我设置为在A列中输入首字母时填写B + C列,但我想在有人在N列中输入另一个值时运行
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range, B As Range, Inte As Range, r As Range
Set A = Range("A:A")
Set Inte = Intersect(A, Target)
If Inte Is Nothing Then Exit Sub
Application.EnableEvents = False
For Each r In Inte
If r.Value > 0 Then
r.Offset(0, 1).Value = Date
r.Offset(0, 1).NumberFormat = "mm-dd-yy"
r.Offset(0, 2).Value = Time
r.Offset(0, 2).NumberFormat = "hh:mm AM/PM"
Else
r.Offset(0, 1).Value = ""
r.Offset(0, 2).Value = ""
End If
Next r
End Sub
答案 0 :(得分:3)
您只需要测试目标范围的地址/位置:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Select Case Target.Column
Case 1 ' "A"
Dim A As Range, B As Range, Inte As Range, r As Range
Set A = Range("A:A")
Set Inte = Intersect(A, Target)
If Inte Is Nothing Then Exit Sub
For Each r In Inte
If r.Value > 0 Then
r.Offset(0, 1).Value = Date
r.Offset(0, 1).NumberFormat = "mm-dd-yy"
r.Offset(0, 2).Value = Time
r.Offset(0, 2).NumberFormat = "hh:mm AM/PM"
Else
r.Offset(0, 1).Value = ""
r.Offset(0, 2).Value = ""
End If
Next r
Case 14 ' "N"
' Do something else
End Select
Application.EnableEvents = True ' <-- Don't forget to turn this back on!
End Sub
此外,由于这种方法可能变得难以处理,因此分解您的方法通常是个好主意。 (较小的方法几乎总是更好。)
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Select Case Target.Column
Case 1, ' "A"
Call AddDatesAfterInitialsEntered(Target)
Case 14 ' "N"
' Do something else
End Select
Application.EnableEvents = True ' <-- Don't forget to turn this back on!
End Sub
Private Sub AddDatesAfterInitialsEntered(Target As Range)
Dim A As Range, B As Range, Inte As Range, r As Range
Set A = Range("A:A")
Set Inte = Intersect(A, Target)
If Inte Is Nothing Then Exit Sub
For Each r In Inte
If r.Value > 0 Then
r.Offset(0, 1).Value = Date
r.Offset(0, 1).NumberFormat = "mm-dd-yy"
r.Offset(0, 2).Value = Time
r.Offset(0, 2).NumberFormat = "hh:mm AM/PM"
Else
r.Offset(0, 1).Value = ""
r.Offset(0, 2).Value = ""
End If
Next r
End Sub