我正在使用事件处理程序,如果选择了一个单元格或两个单元格,我会运行某些事件。我遇到的问题是,当选择两个单元格时,我不知道如何访问第二个单元格的属性(即,它的值是什么)。知道如何访问所选择的第二个单元格的值(我希望Target是一个数组对象,我可以通过数组索引选择....)
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo disError
If Target.Cells.Count > 2 Or Target.Address = Range("DataHist").Address Then Exit Sub
Dim curve As String
Dim Ticker As String
Dim TickerTwo As String
Dim lastValue As Double
TickerTwo = ""
If Target.Cells.Count = 1 Then
Ticker = Target.Value
lastValue = Round(Target.Offset(0, 1).Value, 3)
curve = CheckLabel(Target)
Else
' This is where the issue is --------------------------------
Ticker = Target.Cells(1, 1).Value
TickerTwo = Target.Next.Value
lastValue = Round(Target.Offset(0, 1).Value, 3)
curve = CheckLabel(Target)
' -----------------------------------------------------------
End If
Select Case curve
Case "na"
Exit Sub
Case "Test1"
Call FillChart("Test1", Ticker, lastValue, TickerTwo)
Case "Test2"
Call FillChart("Test2", Ticker, lastValue, TickerTwo)
End Select
disError:
End Sub
答案 0 :(得分:3)
如果您不知道用户是要选择列中的单元格还是行中的单元格,甚至是单元格块,请使用循环和计数器:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim r As Range, i As Long
i = 1
If Target.Count > 1 Then
For Each r In Target
MsgBox r.Address(0, 0) & vbCrLf & i
i = i + 1
Next r
End If
End Sub
然后在 i = 2 时进行处理。如果选择了一个块或行,那么它将是右边的单元格,如果选择了一部分列,它将是下面的单元格。
虽然这是不是漂亮的代码,但至少它会起作用,即使用户选择了一组不相交的单元格。
修改#1:强>
如果您愿意解析Selection.Address
修改#2:强>
如果用户选择2个且只有2个单元格,则此代码(没有任何循环)将起作用:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim s As String
If Target.Count = 2 Then
s = Split(Replace(Target.Address(0, 0), ":", ","), ",")(1)
MsgBox "The second cell is: " & s
End If
End Sub