VBA时间戳执行第一个实例,但不执行第二个实例

时间:2019-10-17 14:57:27

标签: excel vba timestamp

我有一个大型数据集,其中包含许多要更新的不同列。我正在尝试创建一种时间戳记日期/时间,以了解上次更新列的时间。我需要为4个单独的实例执行此操作。

我遇到的问题是,它对于VBA的第一个实例似乎工作正常,但是无论如何都不会在另一列上执行。请在下面查看我的完整代码示例:

Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange1 As Range
Dim myDateTimeRange1 As Range
Dim myUpdatedrange1 As Range

Set myTableRange1 = Range("S:S")

If Intersect(Target, myTableRange1) Is Nothing Then Exit Sub

Set myDateTimeRange1 = Range("A" & Target.Row)
Set myUpdatedrange1 = Range("X" & Target.Row)


If myDateTimeRange1.Value = "" Then
    myDateTimeRange1.Value = Now

End If
myUpdatedrange1.Value = Now

End Sub

Sub Worksheet_Change2(ByVal Target As Range)

Dim myTableRange2 As Range
Dim myDateTimeRange2 As Range
Dim myUpdatedrange2 As Range

Set myTableRange2 = Range("T:T")

If Intersect(Target, myTableRange2) Is Nothing Then Exit Sub

Set myDateTimeRange2 = Range("zz" & Target.Row)
Set myUpdatedrange2 = Range("Y" & Target.Row)


If myDateTimeRange2.Value = "" Then
    myDateTimeRange2.Value = Now

End If
myUpdatedrange2.Value = Now

End Sub

****更新****

我也曾尝试将这些代码合并在一起,如下所示:

Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange1 As Range
Dim myDateTimeRange1 As Range
Dim myUpdatedrange1 As Range
Dim myTableRange2 As Range
Dim myDateTimeRange2 As Range
Dim myUpdatedrange2 As Range

Set myTableRange1 = Range("S:S")
Set myTableRange2 = Range("T:T")

If Intersect(Target, myTableRange1) Is Nothing Then Exit Sub
If Intersect(Target, myTableRange2) Is Nothing Then Exit Sub

Set myDateTimeRange1 = Range("A" & Target.Row)
Set myUpdatedrange1 = Range("X" & Target.Row)
Set myDateTimeRange2 = Range("zz" & Target.Row)
Set myUpdatedrange2 = Range("Y" & Target.Row)


If myDateTimeRange1.Value = "" Then
    myDateTimeRange1.Value = Now
If myDateTimeRange2.Value = "" Then
    myDateTimeRange2.Value = Now

End If
myUpdatedrange1.Value = Now
End If
myUpdatedrange2.Value = Now

End Sub

这导致两者均无效。

我是VBA的新手,所以将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

您需要这样的内容(以大纲形式),以免将更改打折扣到单个列中。

如果仅更改了T,则更新的代码将在到达相关的代码位之前退出。

如果更改了S和T,则只会做S位。

Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange1 As Range
Dim myDateTimeRange1 As Range
Dim myUpdatedrange1 As Range
Dim myTableRange2 As Range
Dim myDateTimeRange2 As Range
Dim myUpdatedrange2 As Range

Set myTableRange1 = Range("S:S")
Set myTableRange2 = Range("T:T")

If Not Intersect(Target, myTableRange1) Is Nothing Then
    'your column S code

ElseIf Not Intersect(Target, myTableRange2) Is Nothing Then
    'your column T code

End If

End Sub