2017-07-04 62 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

相關問題