首页 > 解决方案 > 如何使用更多 Target.Address(范围)

问题描述

在一个单元格中,我列出了一个可供选择的列表。然而,一个选择是不够的。我发现了一些 vba 代码,可以让我做出更多选择。但是这个代码指向一个特定的单元格。我想在工作表中更通用地使用它,可能是一个范围。

我试图输入一个范围,target.address但这不起作用。它也不适用于一个单元格(J3)的范围。我发现从 中删除美元符号后,下面的公式不起作用$j$3

Dim Oldvalue As String
Dim Newvalue As String


On Error GoTo Exitsub
TheCell = ActiveCell

If Target.Address = "$J$13" 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
            Target.Value = Oldvalue & ", " & Newvalue
        End If
    End If
End If
Application.EnableEvents = True

Exitsub:
Application.EnableEvents = True

End Sub

我寻找一种解决方案,可以从多个项目的所有列表中进行选择。应以可在一系列单元格中使用的方式更改公式。这些单元格都有相同的选择列表。

标签: excelvba

解决方案


代替

If Target.Address = "$J$13" Then

您可以将您的范围与您要检查的范围相交:Target

Dim AffectedRange As Range
Set AffectedRange = Intersect(Target, Me.Range("J13:J20")) 'put your range here

If Not AffectedRange Is Nothing Then

    Dim Cell As Range
    For Each Cell In AffectedRange 'loop through all affected cells
        'here use Cell instead of Target
    Next Cell

End If

推荐阅读