excel - 如果目标地址 - 我如何使用范围?

标签 excel vba

您好,我目前正在进行多个列表验证,但目前我只能将其设置为一个单元格 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

最佳答案

使用类似的东西

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

关于excel - 如果目标地址 - 我如何使用范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67900249/

相关文章:

vba - Excel 中的 FOR 循环 - 查找和替换

java - 使用java在Excel中插入存储在数组列表中的数据

arrays - SUMPRODUCT 可以在数组公式中使用吗?

vba - 带有变量运算符的 Excel VBA 数学类型公式不适用于小数

Excel xll 可用于跟踪已进行了哪些 VBA 和其他插件调用、花费的时间和使用的内存?

c++ - 将 __stdcall 与 C++ DLL 一起使用

c# - VB 中的 COM 对象数组

vba - 访问标准 VBA 字枚举

VBA Sort DIR 按字母顺序传输数据

excel - 查找 `find` 方法是否在 Excel VBA 中返回 `nothing`