我正在使用下面的vba代码,我提供了多列示例。 我正在尝试的是,如果我尝试进行更改,则相同的值应该还原到已删除的列标题。 如果对“A1”范围进行任何更改,下面的代码工作正常,但是如果我进行“A1”以外的任何更改,则代码占用太多时间并且循环次数太多。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third" Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
Next i
.Rows(1).Font.Bold = True
End With
End If
============================== 请帮我解决这个问题,提前感谢您的帮助。
答案 0 :(得分:0)
问题是.Cells(1, 1 + i).Value = headers(i)
上的值更改会触发事件本身。你基本上会进入这样一个无休止的执行链。
您应该在执行此宏期间禁用事件,或者检查每个标头。
最简单的解决方案:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
Dim i As Integer
Application.EnableEvents = False 'This fixes your issue.
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third" Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
Next i
.Rows(1).Font.Bold = True
End With
End If
Application.EnableEvents = True
End Sub
答案 1 :(得分:0)
在更改值之前,您必须注意禁用事件。 请尝试以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Header As Variant
If Application.Intersect(Target, Target.Parent.Range("A1:C1")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Header = Array("FIRST", "Second", "Third")
Target.Parent.Range("A1:C1").Value = Header
Application.EnableEvents = True
End Sub