macros删除具有less于4个字符的列中的行

我使用以下代码尝试删除特定“NAME”列中less于4个字符的整行。 (即第1行标题为NAME的列)数据库目前有大约10,000行。 我知道现在的代码是接近的,但是当我尝试运行它时,出现了一个VB错误。 我想我可能是在错误的名字中search特定的列。

Sub Macro2() ' Macro to delete rows if there are less than 4 in the NAME column Dim LR As Long, i As Long Application.ScreenUpdating = False LR = Range("NAME" & Rows.Count).End(xlUp).Row For i = LR To 1 Step -1 If Len(Range("NAME" & i).Value) < 4 Then Rows(i).Delete Next i Application.ScreenUpdating = True End Sub 

编辑:我收到以下行中的VBA错误:

 LR = Range("NAME" & Rows.Count).End(xlUp).Row 

正如其他人在上述评论中提到的那样,你的陈述

 LR = Range("NAME" & Rows.Count).End(xlUp).Row 

并且,

 Len(Range("NAME" & i).Value) 

对于VBA在你的程序中是没有任何意义的,因为它们相当于说。

 Range(Name81).Value '81 is a random number 

除非在工作簿中有一个名为Name81(或任何其他编号)的定义名称,否则该代码将产生运行时错误。

我觉得这个让你想要你想要的:

 Sub Macro2() ' Macro to delete rows if there are less than 4 in the NAME column Dim LR As Long, i As Long, lngCol as Long lngCol = Rows(1).Find("NAME",lookat:=xlWhole).Column 'assumes there will always be a column with "NAME" in row 1 Application.ScreenUpdating = False LR = Cells(Rows.Count, lngCol).End(xlUp).Row For i = LR To 1 Step -1 If Len(Cells(i, lngCol).Value) < 4 Then Rows(i).Delete Next i Application.ScreenUpdating = True End Sub