【问题标题】:How to unselect a range previously selected in VBA Excel如何取消选择以前在 VBA Excel 中选择的范围
【发布时间】:2020-04-22 07:17:29
【问题描述】:

我创建了一个组合框,允许修改所选范围内某些单元格的内容。在组合框中做出选择后,我想取消选择我之前选择的范围。我做了几次尝试,但我无法让它工作。最后,我尝试在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 

【问题讨论】:

  • 只是Select 别的东西。
  • 我想避免选择其他东西,因为这可能会导致未来开发的其他意外故障
  • 您无法取消选择您想要的方式。必须始终选择某些内容:单元格、范围、文本框等对象。
  • 只需选择另一个不重要的单元格,如 A1 或任何其他没有内容的单元格
  • 是的,你们是对的。谢谢。

标签: vba excel


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    sTemp = Application.Selection.Address
    
    'after all manipulations, restore selection
    Application.Range(sTemp).Select
    
    'also, reset copying mode
    Application.CutCopyMode = False
    

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2016-11-14
      • 2016-10-10
      相关资源
      最近更新 更多