如何取消选择以前在VBA Excel中选择的范围

时间:2018-01-13 14:17:31

标签: excel vba excel-vba

我创建了一个组合框,允许修改所选范围内某些单元格的内容。在组合框中做出选择后,我想取消选择之前选择的范围。我做了几次尝试,但我无法使它工作。最后,我尝试在sub ComboBox1_Change()结束之前立即调用另一个子,但它也没有用。有什么建议吗?

Private Sub ComboBox1_Change()
    Dim operatore As String
    Dim op1 As String
    Dim op2 As String
    Dim trovato As Integer
    Dim rng As Range
    Set rng = Selection
    operatore = ComboBox1.Value
    op1 = Left(operatore, 3)
    op2 = Right(operatore, 3)
    trovato = 0

    If rng Is Nothing Then
        MsgBox "Non hai selezionato nessun range di celle!"
        Exit Sub
    End If
    For Each cell In rng
        If (trovato = 2) Then
            Exit For

        ElseIf StrComp(cell.Value, op1) = 0 Then
            trovato = trovato + 1
        End If
    Next cell

    If (trovato < 2) Then
        MsgBox "Operatori non trovati nella selezione!"
        Exit Sub
    Else
        Select Case operatore
            Case "Op1<-->Op2"
                For Each cell In Selection
                    If cell.Value = "Op1" Then
                        cell.Value = "Op2"
                    ElseIf cell.Value = "Op2" Then
                        cell.Value = "Op1"
                    End If
                Next cell
                MsgBox "Scambiato Op1 con Op2"
                Set rng = Nothing
            Case "Op1<-->Op3"
                For Each cell In Selection
                    If cell.Value = "Op1" Then
                        cell.Value = "Op3"
                    ElseIf cell.Value = "Op3" Then
                        cell.Value = "Op1"
                    End If
                Next cell
                MsgBox "Scambiato Op1 con Op3"

        End Select
    End If
    unselect rng
End Sub

Public Sub unselect(dataRange As Range)
    Set dataRange = Nothing
End Sub 

2 个答案:

答案 0 :(得分:1)

考虑将布尔值用作存储状态,然后只需使用If来控制方法

答案 1 :(得分:0)

或者,将之前的状态保存到变量中,例如

sTemp = Application.Selection.Address

'after all manipulations, restore selection
Application.Range(sTemp).Select

'also, reset copying mode
Application.CutCopyMode = False