【问题标题】:Excel VBA get range of user selected range by mouseExcel VBA通​​过鼠标获取用户选择范围的范围
【发布时间】:2011-04-10 20:23:42
【问题描述】:

这不是usedrange 的问题。
例如,在 Excel 中,用户使用鼠标选择一个范围(可能为空),比如说 B4:C12

假设在此之后没有取消选择范围用户按下宏,宏应该告诉 B4:C12

谁能举个例子?

宏应该类似于以下内容:

Sub showrng()
    MsgBox SelectedRange.Address(ReferenceStyle:=xlA1)
End Sub

【问题讨论】:

    标签: vba excel excel-2007 excel-2003


    【解决方案1】:
    Sub macro1()
      MsgBox Selection.Address(ReferenceStyle:=xlA1, _
                               RowAbsolute:=False, ColumnAbsolute:=False)
    End Sub
    

    HTH!

    【讨论】:

    • +1 但 ReferenceStyle:=xlA1 会更符合问题的要求
    【解决方案2】:
    Sub macro1()
      MsgBox Selection.Address
    End Sub
    

    Sub macro1()
        Dim addr as String
        addr = Selection.Address
        msgbox addr
    
        ' Now, as we found the address, according to that... you can also do other operations
    
    End Sub
    

    【讨论】:

      【解决方案3】:

      由于选择可以包括多个独立的范围,因此以下代码显示了该问题的更完整解决方案:

      Public Sub SelectionTest()
      Dim r As Range
      Dim s As String
      
        Select Case Selection.Areas.Count
        Case 0:
          MsgBox "Nothing selected."
        Case 1:
          MsgBox "Selected range: " & Selection.Areas(1).Address(False, False)
        Case Else
          s = ""
          For Each r In Selection.Areas
            s = s + vbNewLine + r.Address(False, False)
          Next r
          MsgBox "Selected several areas:" & s
        End Select
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 1970-01-01
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        相关资源
        最近更新 更多