尝试设置一个范围(“标头”),该范围从包含“ Period”的单元格到包含“ Agent Split”的单元格。在代码末尾,我选择了所有这些范围以确保其正常工作。
我已经调整了以下包含For循环的代码
Sub Rangeheaders_test()
Dim r As Long
Dim endRow As Long
Dim endCell As Range
Dim headers As Range
With ActiveSheet
endRow = 500
For r = 1 To endRow
If .Cells(r, "A").Value = "Period" Then
Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
LookAt:=xlPart, After:=.Cells(r, "A"))
Set headers = .Range(.Cells(r, "A"), endCell)
End If
Next r
End With
headers.Select
End Sub
但是,此代码遍历了范围,仅当我希望选择它们全部以进行测试时才选择最后一个。所以我删除了下面的循环
With ActiveSheet
endRow = 500
r = 1 To endRow
If .Cells(r, "A").Value = "Period" Then
Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
LookAt:=xlPart, After:=.Cells(r, "A"))
Set headers = .Range(.Cells(r, "A"), endCell)
End If
End With
headers.Select
但是现在我收到语法错误或编译错误,原因是Unexpected With或If close并卡住了。我需要定义“然后”条件吗? If Then语句是否甚至必要?我还有其他设置条件的方法吗?
答案 0 :(得分:0)
我从@Jun的深刻见解中意识到,我试图将多个范围存储在一个变量中,这就是我出错的地方。
经过一番研究,我发现在指定范围后可以合并范围的联合方法-我使用.Findnext
方法做到了
Sub findheader()
Dim startcell As Range
Dim rng As Range
Set rng = Range("A1:A500")
Set startcell = rng.Find(what:="Period", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
Dim header1, header2, header3 As Range
Set header1 = Range(startcell, startcell.End(xlToRight))
Set startcell = rng.FindNext(startcell)
Set header2 = Range(startcell, startcell.End(xlToRight))
Set startcell = rng.FindNext(startcell)
Set header3 = Range(startcell, startcell.End(xlToRight))
Dim headers As Range
Set headers = Union(header1, header2, header3)
headers.Select
End Sub