如何使用Excel VBA只读取列时循环访问一系列单元格?

我有一个任务返回特定列中的所有连续行。 它们都将连续有数据,第一个空白行将表示数据的结束。 我用它来find列,并将其传递给我的范围,但我不断收到语法错误。

Dim Col Dim found As Boolean Dim cellRange As Range found = Cells.Find(What:="My_Search_Text", After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate 'Take that column as the range. If (found) Then Col = ActiveCell.Column cellRange = ActiveSheet.Range(Col, ActiveSheet.Range(Col).End(xlDown)).Select 

这里的目标是获得正确的单元格范围并循环遍历它们,但是,我不在循环部分,因为最后一行是根本不起作用的。

那么最后这一行的正确语法是什么?还有更好的方法来完成我正在做的事情吗?

尝试以下我已经testing的select情况。

我已经包含了有关我所做的更改的注释,但如果有任何不清楚的地方,请回答问题。

 Option Explicit Sub FindRange() Dim RangeStart As Range Dim RangeEndPlusOne As Range Dim RangeEntire As Range ' Better to explicitly identify the sheet being searched With Sheets("Source") ' Do not attempt to activate the target cell. Instead get it as a range. ' Are you sure about "LookAt:=xlPart"? "LookAt:=xlWhole" might be better ' I have explicitly started the search from cell A1 rather than the current ' position of the cursor. Set RangeStart = .Cells.Find(What:="My_Search_Text", After:=.Range("A1"), _ LookIn:=xlValues, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If RangeStart Is Nothing Then ' My "My_Search_Text" not found Else ' If the cell below RangeStart is empty, End(xlDown) will jump to ' the bottom of the column or the next cell in the column with a value. ' Search down the column for an empty cell Set RangeEndPlusOne = .Columns(RangeStart.Column).Find(What:="", _ After:=RangeStart, _ LookIn:=xlValues, LookAt:=xlWhole, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) ' I ought to test for not found but I assume there is a blank cell below ' RangeStart Set RangeEntire = .Range(RangeStart, RangeEndPlusOne.Offset(-1, 0)) Debug.Print "Start " & RangeStart.Address Debug.Print "End+1 " & RangeEndPlusOne.Address Debug.Print "Entire " & RangeEntire.Address End If End With End Sub 

在VBA中使用对象时,在分配variables时需要使用关键字Set ,第一个语句应该是:

 Set found = Cells.Find(What:="My_Search_Text", After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) 

顺便说一句,你不能指定使用方法作为Activate 。 所以我在声明结尾删除了它。

那么如何获得最后一排呢?

 LastRow = SheetToCheck.Cells(ActiveCell.Row, ActiveCell.Column).End(xlDown).Row 

这将返回break / blank单元格之前的最后一行。

然后使用以下设置您的范围

 Set cellRange = SheetToCheck.Range(SheetToCheck.Cells(ActiveCell.Row, ActiveCell.Column), SheetToCheck.Cells(LastRow, ActiveCell.Column))