2017-10-17 212 views
1

语句If Target.Address = "$I$2" Then只选择I2单元格。如何在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 = "$I$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

提示:'范围()' – Alfabravo

+0

确定像范围(我:我)'? –

+0

'如果Target.Address =“$ I $ 2”那么'**不**选择一个单元格。 ...它只检查目标的地址是否是'I2' – jsotola

回答

1

你可能要检查的整列的“我”,而不是细胞“I2”。 这种情况应自

If Target.Address = "$I$2" Then 

改为

If Target.Column = 9 Then 

让宏将考虑为完整的列。

+0

你是一个天才!谢谢。有没有办法选择整张纸?或多个列? –

+0

如果你想为完成工作表做,然后删除这个条件。由于代码可能不同,您将不得不通过合适的示例来解释多个部分。 –

+0

“您将不得不通过合适的示例解释多个部分,因为代码可能会有所不同。” - 我可以写'如果Target.Column = 9,10 Then'?我应该一次复制并粘贴一列代码吗? –

相关问题