Excel 格式化此VBA代码的正确方法是什么?
我正在尝试制作一个excel文档,每当在相邻行中输入内容时,它将自动填充A列中的日期。我在网上找到了类似的答案:Excel 格式化此VBA代码的正确方法是什么?,excel,vba,Excel,Vba,我正在尝试制作一个excel文档,每当在相邻行中输入内容时,它将自动填充A列中的日期。我在网上找到了类似的答案: Private Sub Worksheet_Change(ByVal Target As Excel.Range) 'Updated by Extendoffice 2017/10/12 Dim xRg As Range, xCell As Range On Error Resume Next If (Target.Count = 1) Then
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'Updated by Extendoffice 2017/10/12
Dim xRg As Range, xCell As Range
On Error Resume Next
If (Target.Count = 1) Then
If (Not Application.Intersect(Target, Me.Range("B:B")) Is Nothing) Then _
Target.Offset(0, -1) = Date
Application.EnableEvents = False
Set xRg = Application.Intersect(Target.Dependents, Me.Range("B:B"))
If (Not xRg Is Nothing) Then
For Each xCell In xRg
xCell.Offset(0, -1) = Date
Next
End If
Application.EnableEvents = True
End If
End Sub
这会使相邻列自动填充日期。评论部分给出了另一个答案,这正是我想要的功能。Dut由于注释部分的格式,其缩进不存在:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'Updated by Extendoffice 20190924
Dim xRg As Range, xCell As Range
Dim xInt As Integer
On Error Resume Next
If (Target.Count = 1) Then
If (Not Application.Intersect(Target, Me.Range("B:N")) Is Nothing) Then
Application.EnableEvents = False
xInt = Target.Row
Me.Range("A" & xInt).Value = Date
Application.EnableEvents = True
End If
End If
End Sub
该如何正确编写?一般规则
缩进的数量表示相关代码行嵌套的深度。每增加一层嵌套都应使用额外的制表符/4空格
有用的格式化工具
有几个网站会自动为您设置格式,例如:
答复:
更一般:每个代码块都需要一个缩进。代码块是函数或sub、if/else语句、循环(for、while、repeat、do)和with语句的代码。缩进对VBA代码的运行并不重要。投票以POB结束。当编辑回答询问时,这不再是一个合适的问题。
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'Updated by Extendoffice 20190924
Dim xRg As Range, xCell As Range
Dim xInt As Integer
On Error Resume Next
If (Target.Count = 1) Then
If (Not Application.Intersect(Target, Me.Range("B:N")) Is Nothing) Then
Application.EnableEvents = False
xInt = Target.Row
Me.Range("A" & xInt).Value = Date
Application.EnableEvents = True
End If
End If
End Sub