单元格值更改时的 Excel VBA 更改编号格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22750744/
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 VBA Change Number format on Cell value change
提问by user3479230
I am having a little difficulty with some Excel visual basic. Particularly I want to change the format of a column based on the value of a cell. Here's what I have so far.
我在使用一些 Excel 视觉基础知识时遇到了一些困难。特别是我想根据单元格的值更改列的格式。这是我到目前为止所拥有的。
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Range("$b") Then
If Range("$b") = "Date" Then
Range("d:d").NumberFormat = "m/d/yyyy"
ElseIf Range("$b") = "Number" Then
Range("d:d").NumberFormat = "#,##0.00"
End If
End If
End Sub
I am new to using the Target feature so any advice would be helpful.
我是使用 Target 功能的新手,因此任何建议都会有所帮助。
回答by coni2k
I don't think you need to use Target, just the block inside that check should enough. Like this;
我认为您不需要使用 Target,只需检查内部的块就足够了。像这样;
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("B1") = "Date" Then
Range("D:D").NumberFormat = "m/d/yyyy"
ElseIf Range("B1") = "Number" Then
Range("D:D").NumberFormat = "#,##0.00"
End If
End Sub
Then change the value in B1 to "Date" or "Number".
然后将 B1 中的值更改为“日期”或“数字”。
回答by LeafOnWind
If you are looking to tell if a particular cell or range of cells this code works
如果您想判断特定单元格或单元格范围,此代码是否有效
If Not Intersect(Target, Range("A1")) Is Nothing Then
<operations>
End If
This will trigger the < operations > ONLY if the target range intersects range A1. If a macro runs and makes any change to the sheet the option to undo gets wiped out.
仅当目标范围与范围 A1 相交时,才会触发 <操作>。如果宏运行并对工作表进行任何更改,则撤消选项将消失。
Hope this helps.
希望这可以帮助。