400错误Excelmacros

我试图运行一个macros,将删除列中不包含特定值的行。这是我的代码:

Sub deleteRows() Dim count As Integer count = Application.WorksheetFunction.CountA(Range("AF:AF")) Dim i As Integer i = 21 Do While i <= count If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False) Then If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("IAM", Range("B" & i))) = False) Then Rows(i).EntireRow.Delete i = i - 1 count = count - 1 End If End If i = i + 1 Loop End Sub 

现在应该做的是以下几点:

1.)find要通过的行数,并将其设置为count(这个工作)

2.)从第21行开始,在B列中寻找“OSR平台”和“IAM”[这种工作(见下文)]

3.)如果找不到,删除整行并根据需要调整计数和行号(这个工作)

出于某种原因,只要代码到达第一个If语句,就会popup一个带有红色X的错误窗口,其中只显示“400”。 据我所知,我已经把所有的东西都写在句法上,但是显然有些问题。

你可能想要从另一个方向循环开始。 当您删除一条线时,所有以前的线都会被移位。 你解释了这一点,但是反向循环比更好地理解( 比如反正我 ),而不是跟踪我在循环中偏移当前位置的时间:

For i = count To 21 Step -1

另外,你太依赖于Application.WorksheetFunction

(Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False)

InStr(Range("B" & i).value, "OSR Platform") > 0

Application.WorksheetFunction需要更多的处理能力,并且根据您要完成的工作,这可能需要相当长的时间。 对于这个build议的更改,代码大小也会减less,没有它的话就会变得更容易阅读。

你的count也可以在没有A.WF情况下A.WF

  • Excel 2000/03: count = Range("AF65536").End(xlUp).Row
  • Excel 2007/10: count = Range("AF1048576").End(xlUp).Row
  • 版本无关: count = Range("AF" & Rows.Count).End(xlUp).Row

还有一件事是,你可以做(​​而且应该在这种情况下)是把你的If语句合并成一个。

做出这些改变,你会得到:

 Sub deleteRows() Dim count As Integer count = Range("AF" & Rows.Count).End(xlUp).Row Dim i As Integer For i = count To 21 Step -1 If Len(Range("B" & i).value) > 0 Then If InStr(Range("B" & i).value, "OSR Platform") > 0 Or InStr(Range("B" & i).value, "IAM") > 0 Then Range("B" & i).Interior.Color = RGB(255, 0, 0) End If End If Next i End Sub 

如果这没有帮助,那么你能逐行通过代码? 添加一个断点,然后用F8进行操作 。 突出显示代码中的variables,右键单击,select“添加监视…”,单击“确定”( 这里有一个很好的资源来帮助您进行一般的debugging ),并注意以下事项:

  • 哪一行遇到错误?
  • 当这种情况发生时, i的价值是什么? (添加这些variables的帮助来帮助)

这对我有效。 它使用AutoFilter,不需要循环或工作表函数。

 Sub DeleteRows() Dim currentSheet As Excel.Worksheet Dim rngfilter As Excel.Range Dim lastrow As Long, lastcolumn As Long Set currentSheet = ActiveSheet ' get range lastrow = currentSheet.Cells(Excel.Rows.Count, "AF").End(xlUp).Row lastcolumn = currentSheet.Cells(1, Excel.Columns.Count).End(xlToLeft).Column Set rngfilter = currentSheet.Range("A1", currentSheet.Cells(lastrow, lastcolumn)) ' filter by column B criteria rngfilter.AutoFilter Field:=2, Criteria1:="<>*OSR Platform*", Operator:= _ xlAnd, Criteria2:="<>*IAM*" ' delete any visible row greater than row 21 which does not meet above criteria rngfilter.Offset(21).SpecialCells(xlCellTypeVisible).EntireRow.Delete ' remove autofilter arrows currentSheet.AutoFilterMode = False End Sub 

此代码将AutoFilter应用于B列,以查看哪些行不包含B列中的“OSR平台”和“IAM”。然后,只需删除大于21的剩余行。首先在工作簿副本上进行testing。

对这个OzGrid线程的一个巨大点头,因为我永远不会记得过滤后select可见单元格的正确语法。