簡體   English   中英

返回帶間隙范圍的最后一列的列號

[英]Return Column number of last Column of a Range With Gaps

我打算做的是一個宏,它將根據用戶選擇的兩列數據構建一個散點圖。 我需要以某種方式獲得選擇的第二列的內容,以便我可以使用正確的標題。

到目前為止,我已經嘗試了以下方法:

myrng.Columns(myrng.Columns.Count).Column 

這僅返回 1,因為范圍中有間隙。

是否有另一種方法可以處理有間隙的范圍,或者是否有不同的方法來繪制數據然后找到第二個選定的列是什么?

如果r是某個定義的范圍,那么它的限制是:

 
 
 
  
  nLastRow = r.Rows.Count + r.Row - 1 MsgBox ("last row " & nLastRow) nLastColumn = r.Columns.Count + r.Column - 1 MsgBox ("last column " & nLastColumn) nFirstRow = r.Row MsgBox ("first row " & nFirstRow) nFirstColumn = r.Column MsgBox ("first column " & nFirstColumn) numrow = r.Rows.Count MsgBox ("number of rows " & numrow) numcol = r.Columns.Count MsgBox ("number of columns " & numcol)
 
 

編輯#1:

這適用於任何范圍,緊湊或不相交。 如果范圍完全為空,它甚至會起作用。 但是,如果范圍有很多單元格,sub 會很慢。

Sub SlowAgony()
    Dim myrange As Range, r As Range, nLastColumn As Long
    Set myrange = Union(Range("C1:C100"), Range("G1:G100"))

    nLastColumn = 0
    For Each r In myrange
        If r.Column > nLastColumn Then nLastColumn = r.Column
    Next r

    MsgBox nLastColumn
End Sub

編輯#2:

這種方式更快:

Sub ytrewq()
    Dim r As Range, addy As String, ary
    Dim nLastColumn As Long, rr As Range
    Set r = Selection
    addy = r.Address(0, 0)

    If InStr(1, addy, ",") = 0 Then
        nLastColumn = r.Columns.Count + r.Column - 1
    Else
        ary = Split(addy, ",")
        nLastColumn = 0
        For Each a In ary
            Set rr = Range(a)
            If rr.Columns.Count + rr.Column - 1 > nLastColumn Then
                nLastColumn = rr.Columns.Count + rr.Column - 1
            End If
        Next a
    End If

    MsgBox nLastColumn
End Sub

最后一個例程檢查不相交范圍的緊湊組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM