2017-07-31 130 views
-4

首先,我對VBA並不瞭解,也沒有深入瞭解我的知識,這只是一種很少出現的結尾。我只需要一些我已經使用谷歌搜索的代碼的幫助。我需要的是代碼適用於我的工作表中的特定範圍的單元格(E3:E400)。我找到的代碼如下。在Excel單元格的目標範圍中應用VBA代碼

Option Explicit 

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim Oldvalue As String 
Dim Newvalue As String 

Application.EnableEvents = True 
On Error GoTo Exitsub 
If Target.Address = "$C$2" Then 
    If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then 
    GoTo Exitsub 
    Else: If Target.Value = "" Then GoTo Exitsub Else 
    Application.EnableEvents = False 
    Newvalue = Target.Value 
    Application.Undo 
    Oldvalue = Target.Value 
     If Oldvalue = "" Then 
     Target.Value = Newvalue 
     Else 
     If InStr(1, Oldvalue, Newvalue) = 0 Then 
      Target.Value = Oldvalue & ", " & Newvalue 
     Else: 
     Target.Value = Oldvalue 
     End If 
    End If 
    End If 
End If 
Application.EnableEvents = True 
Exitsub: 
Application.EnableEvents = True 
End Sub 

謝謝。

回答

0

使用相交的方法來測試是否在目標範圍內是

Range("E3:E400")
Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim Oldvalue As String 
    Dim Newvalue As String 

    Application.EnableEvents = True 
    On Error GoTo Exitsub 
    If Intersect(Target, Range("E3:E400")) Is Nothing Then Exit Sub 

    If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then 
     GoTo Exitsub 
    Else: If Target.Value = "" Then GoTo Exitsub Else 
     Application.EnableEvents = False 
     Newvalue = Target.Value 
     Application.Undo 
     Oldvalue = Target.Value 
     If Oldvalue = "" Then 
      Target.Value = Newvalue 
     Else 
      If InStr(1, Oldvalue, Newvalue) = 0 Then 
       Target.Value = Oldvalue & ", " & Newvalue 
      Else: 
       Target.Value = Oldvalue 
      End If 
     End If 
    End If 

    Application.EnableEvents = True 
Exitsub: 
    Application.EnableEvents = True 
End Sub 
相關問題