VBA循环无法删除空白和坏字符行

时间:2017-12-22 13:32:15

标签: excel vba excel-vba

你好,所以我正在尝试帮助工作中的工作流程。我们必须导入来自两个不同数据库的两个文件而不是.txt。我创建了一个excel宏,使用get external function选项通过刷新导入两个文件。我会划掉它们,但那是后来的。接下来我想通过并删除列A中具有空格和坏字符的单元格从第A2行开始。由于我的工作,我真的很新,并且不需要长时间编写脚本。这就是我所拥有的,并试图调整。现在循环删除了几乎所有东西!!请帮忙。是的,我已经在所有论坛上寻求帮助,但没有任何效果。

$path = '/usr/pathToYourDir';

3 个答案:

答案 0 :(得分:1)

Rows(LR).Delete而不是Cells(i).EntireRow.Delete呢?

答案 1 :(得分:0)

您实际上是从Array而不是row删除了该位置。因此,你犯了两个错误。

请尝试:

Cells(RowNbr, 1).EntireRow.Delete

而不是:

Cells(i).EntireRow.Delete

有一个小技巧"在VBA。

当您向Cells()提供2个参数时,第一个是一行,第二个是一列。但是,如果您只提供一个参数,那么它就是一个列。

因此Cells(5)E1而不是A5正如您所期待的那样。因此,它几乎总是从代码中删除第一个单元格。

此外,每次都会重新计算您查找最后一列的方式,这可能很危险。尝试在那里使用变量:

For ColNbr = 1 To Cells.Find("*", so:=xlByRows, searchdirection:=xlPrevious).Column

答案 2 :(得分:0)

所以我把它像这样并从数组“*”中删除,因为这意味着所有行都被删除

Option Explicit

Public Sub DeleteBadRows()

    Dim RowNbR As Long
    Dim BadChr() As Variant
    Dim LR As Long
    Dim wb As Workbook
    Dim wsSource As Worksheet
    Dim lastCol As Long

    Set wb = ThisWorkbook
    Set wsSource = wb.Worksheets("Sheet1")

    Dim rngDelete As Range
    BadChr = Array("=", ",FEE", "DATE 12/13", ",(", "SMSLIST O", "REQUEST T", "WHERE", "SVC") 'include any characters to trigger deletion of row

    LR = wsSource.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    lastCol = wsSource.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column

    For RowNbR = 1 To LR

        If WasFound(wsSource, BadChr, RowNbR) Then

            If Not rngDelete Is Nothing Then

                Set rngDelete = Union(rngDelete, wsSource.Cells.Rows(RowNbR).EntireRow)

            Else
                Set rngDelete = wsSource.Cells.Rows(RowNbR).EntireRow

            End If
        End If


    Next RowNbR

    If Not rngDelete Is Nothing Then rngDelete.EntireRow.Delete
End Sub


Private Function WasFound(ByRef wsSource As Worksheet, ByVal BadChr As Variant, ByVal RowNbR As Long) As Boolean
 Dim i As Long

 WasFound = False

 For i = LBound(BadChr) To UBound(BadChr)

          Dim found As Long

            On Error Resume Next
            found = wsSource.Cells(RowNbR, 1).EntireRow.Find(What:=BadChr(i), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
            On Error GoTo 0

            If found > 0 Then

                 WasFound = True

                Exit Function
            End If

       Next i

End Function