首页 > 解决方案 > 如果目标地址 - 我如何使用范围?

问题描述

嗨,我目前正在进行多列表验证,但目前我只能将其添加到一个单元格 E2,并且我希望将其设置在从 E2:E40 开始的范围内。我在考虑$E$2:$E$40。但是,这不起作用。

Private Sub Worksheet_Change(ByVal Target As Range)
' To allow multiple selections in a Drop Down List in Excel (without repetition)
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Address = "$E$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

标签: excelvba

解决方案


使用这样的东西

Dim AffectedCells As Range
Set AffectedCells = Intersect(Me.Range("E2:E40"), Target)

If Not AffectedCells Is Nothing Then
    ' do your stuff here …
End If

AffectedCells包含E2:E40其中实际更改的所有单元格。

确保循环AffectedCells处理每个单元格

Dim Cell As Range
For Each Cell In AffectedCells.Cells
    ' do your stuff with each Cell here …
Next Cell

推荐阅读