根据标题名称删除行

我试图删除我的Excel表中的很多行。

我的VBA非常简单:

Sub delNA() lr = Cells(Rows.Count, "A").End(xlUp).Row 'find last row For i = lr To 2 Step -1 'loop thru backwards, finish at 2 for headers If Cells(i, "H").Text = "#N/A" Then Rows(i).EntireRow.Delete Next i End Sub 

但我的问题是,有时我的标题是不同的。 在这种情况下,头BTEX(总和)在H2,但有时该参数是在G2,有时它在E2,所以我想要做的是使VBAsearch头名称,所以而不是H标准是“BTEX(Sum)”。

有没有办法让VBA在第2行的值为“BTEX(Sum)”的列中运行

试试这个:

 Option Explicit Sub delNA() Const HEADER_TEXT As String = "BTEX (Sum)" Dim thisSheet As Worksheet Set thisSheet = ActiveSheet With thisSheet Dim myHeader As Range Set myHeader = .Cells.Find(What:=HEADER_TEXT, after:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not myHeader Is Nothing Then 'ie we found the header text somewhere Dim headerColumn As Long headerColumn = myHeader.Column Dim lastRow As Long 'Update here: lastRow = .Cells(.Rows.Count, headerColumn).End(xlUp).Row 'find last row Dim i As Long For i = lastRow To 2 Step -1 'loop thru backwards, finish at 2 for headers 'Update here: If IsError(.Cells(i, headerColumn).Value2) Then .Rows(i).EntireRow.Delete End If Next i Else MsgBox ("Could not find a column for the header text " & HEADER_TEXT) End If End With End Sub 
  • 它使用范围上的.Find()来非常快速地标识你的标题列的位置,如果没有find它,popup错误消息(以防万一)
    • 注意: .Find()将使用Find对话框中没有明确设置的任何内容的当前设置,下次使用Find对话框时,设置将是代码设置的内容。 即Find对话框和.Find()函数共享一组共同的,持久的参数。
  • 它将一个工作表variables分配给当前工作表,只是为了确保如果这个应该运行一段时间,一个无聊的用户不会点击另一个工作表并打破东西。
  • 所有的工作表行通过使用.Cells().Rows() (注意.Cells()明确地引用thisSheet ,因为这一行: With thisSheet
  • 它使用.Value2而不是.text (请参阅这里的原因。)
  • 我在开头声明了Option Explicit ,以确保在使用之前声明所有的variables。
    • 这是一个很好的习惯,因为它可以消除在一个地方使用MyText作为variables并且MyTxt作为其他地方的variables而不理解为什么MyTxt令人沮丧的错误。
  • 现在,您可以通过将Const声明转换为由delNA()接受的参数来构build更通用的函数,您可以将其用于任何标题行而不是固定标题行。

@Mikkel Astrup你首先使用for循环find你正在寻找的列索引,在这种情况下,第二行的单元格的列索引的值是“BTEX(Sum)”

 Dim lColumn,indexCol As Long dim ws as worksheet dim headerKey as string set ws = thisworkbook.worksheets("Sheet1") lColumn = ws.Cells(2, Columns.Count).End(xlToLeft).Column headerKey = "BTEX (Sum)" for indexCol = 1 to lColumn step 1 if ws.cells(2,indexCol).value = headerKey then ' your code ' indexCol is the index of col you are looking for' exit for ' exit the loop now end if Next