【问题标题】:Apply VBA macro to multiple cells将 VBA 宏应用于多个单元格
【发布时间】:2017-08-30 12:43:52
【问题描述】:

我会说我不是 VBA 专家。我有一个 VBA 代码,可将选定列表中的多个值附加到一个单元格中。该代码有效,但现在我想将该代码应用于多个单元格。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
'Code by Sumit Bansal from https://trumpexcel.com
' To Select Multiple Items from a Drop Down List in Excel
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Address = "$A$7" 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 & "," & Chr(10) & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub

如何扩展我的代码以使用单元格范围

$A$7:$A$18 

而不是 "$A$7",以便我可以将 VBA 代码应用于 Excel 中的多个单元格。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    改变

    If Target.Address = "$A$7" Then
    

    If Not Intersect(Target, Range("A7:A18")) Is Nothing Then
    

    【讨论】:

      【解决方案2】:

      我使用了通配符。

      If Target.Address = "$A$7" Then
      

      If Target.Address Like "$A$[7-9]" Or Target.Address Like "$A$1[0-8]" Then
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 2014-02-11
        • 2013-07-11
        • 2021-09-01
        • 1970-01-01
        相关资源
        最近更新 更多