我正在使用事件处理程序,并且如果选择一个或两个单元格,则会运行某些事件。我遇到的问题是,当选择两个单元格时,我不知道如何访问该第二个单元格的属性(即,它的值是多少)。任何想法,我如何可以访问所选的第二个单元格的值(我希望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

最佳答案

如果您不知道用户是要选择列中的单元格还是行中的单元格,甚至是单元格块,请使用循环和计数器:

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

关于excel - Worksheet_SelectionChange(ByVal目标为范围),目标中有两个单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48308883/

10-16 17:12