vba Excel:在单元格单击上运行宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25203227/
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
Excel: Run A Macro On Cell Click
提问by mark jay
I am using the following code to insert todays date into a cell when a user clicks onto another cell in that row.
当用户单击该行中的另一个单元格时,我使用以下代码将今天的日期插入到该单元格中。
At the moment the code is set out like so; if a user clicks cell AQ8 then insert date into cell AS8.
目前代码是这样设置的;如果用户单击单元格 AQ8,则将日期插入单元格 AS8。
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Address = "$AQ" Then
       Range("AS8").Value = DATE
    End If
End Sub
however, now i want to change this code slightly so that when a user changes any AQ cell in either row then the subsequent AS cell has the date inserted into the appropriate cell for that row. So if cell AQ9 is clicked then AS9 shows todays date and when they click AQ10 then AS10 shows todays date and so on. Would this be written as a target row function? and if so how would i write something like this? Can someone please show me how i could get this to do what i need, thanks in advance
但是,现在我想稍微更改此代码,以便当用户更改任一行中的任何 AQ 单元格时,随后的 AS 单元格会将日期插入到该行的相应单元格中。因此,如果单击单元格 AQ9 然后 AS9 显示今天的日期,当他们单击 AQ10 然后 AS10 显示今天的日期等等。这会被写成目标行函数吗?如果是这样,我将如何写这样的东西?有人可以告诉我如何让这个做我需要的,提前致谢
采纳答案by djikay
If you don't want to refer to columns by number, i.e. you want to use "AQ" instead of 43, then the following should work:
如果您不想按数字引用列,即您想使用“AQ”而不是 43,那么以下应该有效:
Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = Range("AQ1").Column Then
    Range("AS" & Target.Row).Value = Date
  End If
End Sub
The reference to row 1 in AQ1is a dummy, since the code just selects the .Columnof that range.
对第 1 行的引用AQ1是虚拟的,因为代码只选择了.Column该范围的 。
I'm using Worksheet_Changebecause you said "when a user changesany AQ cell". If you only want this to happen when a user clickson a cell, then you can keep using the Worksheet_SelectionChangeevent.
我使用Worksheet_Change是因为您说“当用户更改任何 AQ 单元时”。如果您只希望在用户单击单元格时发生这种情况,那么您可以继续使用该Worksheet_SelectionChange事件。
回答by user3514930
Update like that:
像这样更新:
If Target.Column = 43 Then
   Range("AS" & Target.Row).Value = Date
End If
every rows in column AQ = 43 are updated with the date.
列 AQ = 43 中的每一行都更新为日期。

