vba 更改命名范围(单元格)时如何调用宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22792609/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:37:07  来源:igfitidea点击:

How to call a Macro when a named range (cell) is changed

excelvbaexcel-vbanamed-ranges

提问by Anonymous N

I am trying to call a macro named "RE_environmental" when the cell named "RE_1" is changed (i.e. they mark a X in the cell). I've tried several different variations of codes including these two and nothing is happening:

当名为“RE_1”的单元格更改时(即它们在单元格中标记一个 X),我试图调用一个名为“RE_environmental”的宏。我尝试了几种不同的代码变体,包括这两个,但没有任何反应:

[The first code does work if I use the exact cell location and not the named cell. --> $E$62]

[如果我使用确切的单元格位置而不是命名单元格,则第一个代码确实有效。--> 62 美元]

     Private Sub Worksheet_Change(ByVal Target As Range)

     If Target.Address = "RE_1" Then

     Call RE_environmental

     End If

     End Sub

AND

     Private Sub Worksheet_Change(ByVal Target As Range)

     If Range("Name").Select = "RE_1" Then

     Call RE_environmental

     End If

     End Sub

--Thanks in Advanced and please let me know if you need more information.

--感谢高级版,如果您需要更多信息,请告诉我。

回答by Dmitry Pavliv

If Targetis always single-cell range, you can use this one:

如果Target总是单细胞范围,你可以使用这个:

If Target.Address = Range("RE_1").Address Then
    Call RE_environmental
End If

If Targetcan be multicell range use this one:

如果Target可以是多单元格范围使用这个:

If Not Intersect(Target, Range("RE_1")) Is Nothing Then
    Call RE_environmental
End If

回答by Mike Medina

Use your first answer but make this small change:

使用你的第一个答案,但做这个小改动:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Range("RE_1").Address Then

        Call RE_environmental

    End If

End Sub

Simple syntax mistake!

简单的语法错误!

Edit: To stop RE_environmental from running once the cell is empty, put the code from RE_environmental inside a do-while (not isempty(Range("RE_1"))) as long as RE_environmental is emptying "RE_1". The user won't be able to edit cells while RE_environmental is running.

编辑:要在单元格为空后停止 RE_environmental 运行,只要 RE_environmental 正在清空“RE_1”,就将来自 RE_environmental 的代码放在 do-while 中(不是 isempty(Range("RE_1")))。当 RE_environmental 运行时,用户将无法编辑单元格。