我正在尝试将两个不同的功能合并到一个私有Sub下,但仍然会收到“Block If If End End If”错误。似乎无法解决这个问题。我试图让它工作,但一直得到同样的错误?
代码:
Private Sub Worksheet_Change(ByVal Target As Range)
'Fill in Date when checked.
Dim rngColJ As Range
Dim rngColA As Range
Dim Rng As Range
Dim Rngg As Range
Dim xOffsetColumn As Integer
Set rngColJ = Intersect(Application.ActiveSheet.Range("J:J"), Target)
xOffsetColumn = 20
Application.EnableEvents = False
If Not rngColJ Is Nothing Then
For Each Rng In rngColJ
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "mm-dd-yyyy, hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
Set rngColA = Intersect(Application.ActiveSheet.Range("A:A"), Target)
xOffsetColumn = 4
If Not rngColA Is Nothing Then
For Each Rng In rngColA
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "m/d/yyyy"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
Application.EnableEvents = True
End Sub
答案 0 :(得分:0)
您没有Next
与For Each Rng In WorkRng
相关联。
另请注意:您的Application.EnableEvents
位于If Not WorkRngg
区域内,因此,从结构上看,您似乎与循环和if语句不匹配。
现在的问题是编译器很困惑,因为当For Each
循环应该遇到End If
时遇到Next
循环。当然它并不知道,它只知道你所拥有的在语法上是不正确的。
像这样:
If Not WorkRng Is Nothing Then
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "mm-dd-yyyy, hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
If Not WorkRngg Is Nothing Then
For Each Rngg In WorkRngg
If Not VBA.IsEmpty(Rng.Value) Then '<~~ possibly this should be (Rngg.Value)?
Rngg.Offset(0, xOffsetColumn).Value = Now
Rngg.Offset(0, xOffsetColumn).NumberFormat = "m/d/yyyy"
Else
Rngg.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
Application.EnableEvents = True
End Sub
我还建议找到一个比Rng
和Rngg
更好的命名约定等等。它很容易解决难以解决的印刷错误,如你可以在For Each Rngg in WorkRngg
循环中完成。
由于您使用Rng
作为迭代器,因此您不需要两者。只需在两个循环中使用Rng
即可。如果您同时使用两个不同的范围,那么您只需要两个变量。这样:
Private Sub Worksheet_Change(ByVal Target As Range)
'Fill in Date when checked.
Dim rngColJ As Range
Dim rngColA As Range
Dim Rng As Range
Dim Rngg As Range
Dim xOffsetColumn As Integer
Set rngColJ = Intersect(Application.ActiveSheet.Range("J:J"), Target)
Set rngColA = Intersect(Application.ActiveSheet.Range("A:A"), Target)
Application.EnableEvents = False
If Not rngColJ Is Nothing Then
xOffsetColumn = 20
For Each Rng In rngColJ
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "mm-dd-yyyy, hh:mm:ss"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
If Not rngColA Is Nothing Then
xOffsetColumn = 4
For Each Rng In rngColA
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "m/d/yyyy"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
End If
Application.EnableEvents = True
End Sub