2017-07-04 256 views
0

我使用下面的VBA代码,我有多个样本列我已经提供了几个。 我所尝试的是,如果我尝试进行更改相同的值应恢复到删除列标题。 下面的代码工作正常,如果我对范围“A1”进行了任何更改,但是如果我进行除“A1”之外的任何更改,则代码花费太多时间完成并且循环太多次。如何将数组值添加到列使用Excel VBA

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

你有你改变数值前采取致残事件的照顾。 请尝试以下代码:

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 
+0

非常感谢您的帮助。它的工作 – Rick

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 
+0

非常感谢你,它的工作如预期。 – Rick

+0

非常感谢,它按预期工作。 1)但是,我有一个问题,“Option Explicit”的用途是什么?因为即使没有“Option Explicit”代码段,代码也能正常工作。 2)我需要在列“A”(A2到A100)中使用VBA(“One”和“Two”)添加具有两个值的LOV。但是,如果我复制粘贴其他一些值,例如“三”,这应该覆盖,但仍然可以选择原始值(“一”和“两”)的LOV。 请告诉我,再次感谢您的帮助。 – Rick