简体   繁体   English

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

[英]How to unselect a range previously selected in VBA Excel

I have create a combobox that permit to modify the content some cells in a range selected.我创建了一个组合框,允许修改选定范围内某些单元格的内容。 After making a choice in the combobox, I would like to unselect the range that I have selected before.在组合框中做出选择后,我想取消选择我之前选择的范围。 I have make several attempts but I couldn't make it work.我已经进行了几次尝试,但我无法使其正常工作。 Finally I try to call another sub just immediately before the end of the sub ComboBox1_Change() but it didn't work, either.最后,我尝试在sub ComboBox1_Change()结束之前立即调用另一个子,但它也不起作用。 Any suggestions?有什么建议吗?

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 

考虑使用布尔值作为存储状态,然后简单地使用 If 来控制您的方法

Or, save state before into variable, like或者,将之前的状态保存到变量中,例如

sTemp = Application.Selection.Address

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

'also, reset copying mode
Application.CutCopyMode = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM