带有循环语句的Excel VBA代码问题-对象变量或未设置块变量

问题描述 投票:1回答:1

我正在尝试包含将通过D列,搜索X条目并执行必要操作的代码。这将一直起作用,直到找到带有条目END的单元格为止。此时,我收到一条错误消息:对象变量或未设置块变量我做错了吗?

Sub Example

Range("Cl").Select 
Selection.End(xlDown).Select 
ActiveCell.Offset(l, 1).Range("Al").Select 
ActiveCell.FormulaRlCl = "END"

Dim CellsFound As Range 
 Range("dl").Select 'ActiveCell.Range("al:al000").Select
Set CellsFound = ActiveCell.Range("al:al000") Do Until ActiveCell = "END"
 Cells.Find(What:="X", After:=ActiveCell, Lookin:=xlFormulas, LookAt
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= True, 
 SearchFormat:=False).Activate
 ActiveCell.Range("Al:Gl").Select Selection.Delete Shift:=xlToLeft

 End Sub
excel vba
1个回答
0
投票

我相信以下内容将帮助您实现所需的结果,它使用For循环遍历行,检查D列中单元格的值,如果X然后删除A:G,如果END然后退出子:

Sub Example()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
'get the last row with data on Column D

For i = 2 To LastRow
'loop from Row 2 to the last
    If ws.Cells(i, "D").Value = "X" Then ws.Range("A" & i & ":G" & i).Delete Shift:=xlToLeft
    'if Column D contains "X" then delete A:G on that row
    If ws.Cells(i, "D").Value = "END" Then Exit Sub
    'if Column D contains "END" then Exit Subroutine
Next i
End Sub

循环遍历行的一种替代方法是先过滤它们,然后删除所有可见行,下面是一个示例:

Sub Example()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
'get the last row with data on Column D
ws.Cells.AutoFilter
ws.Range("$A$1:$G$" & LastRow).AutoFilter Field:=4, Criteria1:="X"
'filter Column 4 (D) for any row where it contains "X"
ws.Range("$A$2:$G$" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete 'Shift:=xlLeft
'delete any visible rows after filtering
ws.ShowAllData
'Clear filter criteria
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.