如果找到字符串,请删除一行

时间:2018-04-06 16:37:58

标签: excel vba excel-vba

我正在编写一段代码,我希望按以下标准删除多余的空行

  • 该行实际上是空的
  • 这不是总排

我通过以下代码执行此操作,该代码在某个单元格中搜索值为0,然后我希望它在字符串中查找单词Total,如果这两个条件都是,则不激活if语句不符合

目前我的Instr功能无效,所以我需要以某种方式改变它。

Sub Clean_HB()

Dim CLEANHBWS As Worksheet
Set CLEANHBWS = Sheets("Hedgebook")
Dim CLEANFormulaWS As Worksheet
Set CLEANFormulaWS = Sheets("Formula_Template")
Dim Cleanrange As Range

CLEANLastHBR = CLEANHBWS.Cells(CLEANHBWS.Rows.Count, "B").End(xlUp).Row
CLEANClastHBC = CLEANHBWS.Cells(3, CLEANHBWS.Columns.Count).End(xlToLeft).Column
CLEANLastFWSR = CLEANFormulaWS.Cells(CLEANFormulaWS.Rows.Count, "B").End(xlUp).Row
CLEANCLASTFWSC = CLEANFormulaWS.Cells(3, CLEANFormulaWS.Columns.Count).End(xlToLeft).Column

CLEANTickercolumn = CLEANHBWS.Cells.Find(What:="Ticker").Column
CLEANDatecolumn = CLEANHBWS.Cells.Find(What:="Date&Time Booked").Column
CLEANLScolumn = CLEANHBWS.Cells.Find(What:="L/S").Column
CLEANLotscolumn = CLEANHBWS.Cells.Find(What:="Lots").Column
CLEANConversioncolumn = CLEANHBWS.Cells.Find(What:="Conversion Cents").Column
CLEANBorrowcolumn = CLEANHBWS.Cells.Find(What:="Borrow (bps)").Column

For Each Cleanrange In CLEANHBWS.Range(Cells(3, CLEANLotscolumn), Cells(CLEANLastHBR, CLEANLotscolumn))
    If Cleanrange.Value = 0 And Cleanrange.Offset(0, -4).Value <> InStr(1, "total") Then
    Cleanrange.Rows.Select
    Cleanrange.EntireRow.Select
    Selection.Delete
    End If
Next

End Sub

编辑:工作簿的图片,其中Lots列是我希望它检查零或空白的列,而Date / Time列也用作Total标题列

enter image description here

感谢任何建议

1 个答案:

答案 0 :(得分:2)

您正在寻找类似下面代码的内容,代码注释中的解释:

Dim DelRng As Range ' define a range that will store all rows that needs to be deleted 

' need to add CLEANHBWS also before Cells, to qualify with the sheet you want, and not ActiveSheet 
For Each Cleanrange In CLEANHBWS.Range(CLEANHBWS.Cells(3, CLEANLotscolumn), CLEANHBWS.Cells(CLEANLastHBR, CLEANLotscolumn))
    ' check if cell is empty or equals 0 and not "total" row
    If (Cleanrange.Value = 0 Or Trim(Cleanrange.Value) = "") And InStr(Cleanrange.Offset(0, -4).Value, "total") = 0 Then
        If Not DelRng Is Nothing Then
            Set DelRng = Application.Union(DelRng, Cleanrange)
        Else
            Set DelRng = Cleanrange
        End If
    End If
Next
' make sure there is at least 1 cell inside the range >> delete entire range at 1 line
If Not DelRng Is Nothing Then DelRng.EntireRow.Delete