粘贴数据时自动运行宏 VBA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24273309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatically Run Macro When Data Is Pasted VBA
提问by Dubeddo
I have a worksheet where in the first three columns (A,B,C) I store data. These values are used in a macro.
我有一个工作表,在前三列(A、B、C)中存储数据。这些值在宏中使用。
I would like to know how it is possible to make this macro run automatically after data is pasted onto these columns. I am almost sure that I will use the Worksheet-Change module, but as for the code I am clueless.
我想知道如何在将数据粘贴到这些列后自动运行此宏。我几乎可以肯定我会使用 Worksheet-Change 模块,但至于代码,我一无所知。
Thanks in advance.
提前致谢。
采纳答案by Haris
A simple implementation:
一个简单的实现:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:C" & ThisWorkbook.Worksheets(1).UsedRange.Rows.Count)) Is Nothing Then
'Call your Macro to do stuff
End If
End Sub
Intersect checks if Target is in the range you want to monitor. So if something changes in columns past C, Intersect will return Nothing and your macro won't be called. Just keep in mind that the Worksheet_Change event fires on any change, even double clicking into the cells. If all you are doing in this Worksheet is copy&pasting data and then running your Macro, this should be fine, but if you are manipulating your data further, you might have to look at more sophisticated solutions. Examples include mirroring your Worksheet and comparing it pre/post Worksheet Changed Event. You can read more on this here: Detect whether cell value was actually changed by editing
相交检查 Target 是否在您要监视的范围内。因此,如果 C 之后的列中的某些内容发生变化,则 Intersect 将返回 Nothing 并且不会调用您的宏。请记住,Worksheet_Change 事件会在任何更改时触发,甚至双击单元格。如果您在此工作表中所做的只是复制和粘贴数据,然后运行宏,这应该没问题,但如果您要进一步操作数据,则可能需要查看更复杂的解决方案。示例包括镜像您的工作表并在工作表更改事件之前/之后进行比较。您可以在此处阅读更多相关信息:检测单元格值是否已通过编辑实际更改