2017-07-31 129 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 
相关问题