根据标题名称

时间:2017-09-07 12:07:09

标签: excel vba excel-vba

我试图删除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(Sum)在H2中,但有时该参数在G2中,有时它在E2中,所以我试图做的是让VBA搜索标题名称,所以不是H而是标准是" BTEX(Sum)"。

有没有办法让VBA在第2行中的值为" BTEX(Sum)"

的列中运行

2 个答案:

答案 0 :(得分:1)

@Mikkel Astrup你首先只需使用for循环来查找你要查找的col索引,在这种情况下,第2行中单元格的col索引具有值" 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

答案 1 :(得分:1)

尝试一下:

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  'i.e. 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()将使用Find对话框中未明确设置的任何内容的当前设置,并在您下次使用Find对话框时,设置将是您的代码设置的任何设置。即Find对话框和.Find()函数共享一组常见的持久参数。
  • 它将工作表变量分配给当前工作表,只是为了确保如果这应该运行一段时间,一个无聊的用户不会点击另一个工作表并破坏内容。
  • 所有工作表行使用thisSheet.Cells()明确引用.Rows()(请注意引导.),因为该行:With thisSheet
  • 它使用.Value2代替.text(请参阅here。)
  • 我在开头声明Option Explicit以确保在使用之前声明所有变量。
    • 这是一个很好的习惯,因为它可以消除令人沮丧的错误,即在一个地方使用MyText作为变量而在其他地方使用MyTxt作为变量而不理解为什么它不是'工作。
  • 现在,您可以通过将Const声明转换为delNA()接受的参数来构建更通用的函数,并将其用于任何标头行而不是这个固定的行。
相关问题