excel 如何将列设置为范围变量,只要列中有数据?

x33g5p2x  于 2023-02-17  发布在  其他
关注(0)|答案(2)|浏览(150)

我希望excel将标题为“Section”的整列输入到范围变量“sectioncol”中。

Set sectioncol = range(range("A1:R1").Find(what:="Section", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False).Address & ":" & range("A1:R1").Find(what:="Section", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False).End(xlDown).Address)

我希望range变量返回section列下包含数据的单元格。

8wigbo56

8wigbo561#

该行太长(难以读取),如果找不到"Section",该行将失败。
最好把它分成几个中间步骤:

Dim rng As Range
Set rng = Range("A1:R1").Find( _
    What:="Section", LookIn:=xlValues, _
    LookAt:=xlWhole, MatchCase:=False)

If Not rng Is Nothing Then ' Test if Section was found
    Dim sectioncol As Range
    Set sectioncol = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
End If
nc1teljy

nc1teljy2#

引用数据列区域

(长)教育(使用Find

Sub ReferenceDataColumnRange()

    ' Define constants.
    Const HEADER_TITLE As String = "Section"
    
    ' Reference the worksheet.
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    ' Reference the table range.
    Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion
    Debug.Print "Entire Range:      " & rg.Address(0, 0)
    
    ' Reference the header row range.
    Dim hrg As Range: Set hrg = rg.Rows(1)
    Debug.Print "Header Row Range:  " & hrg.Address(0, 0)
    
    ' Attempt to reference the header cell.
    Dim hCell As Range: Set hCell = hrg.Find(HEADER_TITLE, _
        hrg.Cells(hrg.Cells.Count), xlFormulas, xlWhole)
    
    ' Check if the header cell was found (referenced).
    If hCell Is Nothing Then
        MsgBox "The header """ & HEADER_TITLE & """ was not found.", vbCritical
        Exit Sub
    End If
    Debug.Print "Header Cell:       " & hCell.Address(0, 0) _
    
    ' Check if there is any data below the headers.
    If rg.Rows.Count = 1 Then
        MsgBox "No data below the header """ & HEADER_TITLE & """.", vbCritical
        Exit Sub
    End If
   
    ' Reference the data column range (no headers).
    Dim crg As Range: Set crg = rg.Columns(hCell.Column - rg.Column + 1) _
        .Resize(rg.Rows.Count - 1).Offset(1)
    Debug.Print "Data Column Range: " & crg.Address(0, 0)

End Sub

(简短)实用(使用Application.Match

Sub ReferenceDataColumnRangeShort()
    
    Dim crg As Range
    
    With ActiveSheet.Range("A1").CurrentRegion
        Dim cIndex: cIndex = Application.Match("Section", .Rows(1), 0)
        If IsNumeric(cIndex) Then ' header found
            If .Rows.Count > 1 Then ' data found
                Set crg = .Columns(cIndex).Resize(.Rows.Count - 1).Offset(1)
            End If
        End If
    End With
    
    If crg Is Nothing Then Exit Sub
    
    MsgBox crg.Address(0, 0), vbInformation

End Sub
  • 请注意,您也可以用简短的版本编写第一段代码。
  • 在每个特定情况下,由您来确定哪些细节是重要的(已知的)。

相关问题