VBA初学者问题:相同的宏以不同的方式显示不同的行为

时间:2018-11-23 13:40:17

标签: excel vba excel-vba

我有以下问题: 您在下面看到的代码已粘贴到excel对象中

Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Application.ScreenUpdating = False
Dim DAY, other As Range
Set DAY = Range("b4:af4")

If Not Intersect(DAY, Range(Target.Address)) Is Nothing Then
ActiveCell.Copy
Sheets("SP Analysis").Activate
Range("b2").PasteSpecial Paste:=xlPasteValues

'ElseIf Not Intersect(other, Range(Target.Address)) Is Nothing Then

End If
End Sub

宏会运行,但不会在工作表SP Analysis中复制活动单元。

如果我使用以下内容更改代码:

Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Application.ScreenUpdating = False Dim DAY, other As Range Set DAY = Range("b4:af4")

If Not Intersect(DAY, Range(Target.Address)) Is Nothing Then Call TEST

'ElseIf Not Intersect(other, Range(Target.Address)) Is Nothing Then End If End Sub

进行宏测试

sub test
  ActiveCell.Copy
Sheets("SP Analysis").Activate
Range("b2").PasteSpecial Paste:=xlPasteValues
end sub

该命令执行应做的事情。 问题是为什么?一种方法与另一种方法有什么区别? 而且,如何使该命令在excel对象中运行,而不必调用宏?

谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下。使用Target而不是ActiveCell,尽管在这种情况下我不知道为什么后者不起作用。而且我们可以直接转移值,而无需激活任何东西。

Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

Application.ScreenUpdating = False

Dim DAY As Range, other As Range   'need to specify type for each variable, otherwise Variant
Set DAY = Range("b4:af4")

If Not Intersect(DAY, Target) Is Nothing Then
    Cancel=True
    Sheets("SP Analysis").Range("b2").Value = Target.Value  'use target
End If

Application.ScreenUpdating = True   'turn it back on

End Sub