从VBE中删除Excel中的行

时间:2016-02-28 21:32:06

标签: vb.net excel vb.net-2010

我有一些代码在excel文件中查找包含与文本框相同字符的记录。然后我需要删除该行,但我不知道该怎么做。请有人帮帮我吗? 这是我的代码:

Dim oXL As Excel.Application
    Dim oSheet As Excel.Worksheet
    Dim oRng As Excel.Range
    'create object and open workbook
    oXL = CreateObject("Excel.application")
    oXL.Workbooks.Open(CreateAdmin.FileLocation + "\DVDRental.xls")

    'open worksheet
    oSheet = oXL.ActiveWorkbook.Sheets("Logins")

    oRng = oSheet.Range("A1:A100")

    Dim blankspace As Integer = 1

    Do Until oRng(blankspace, 2).value() = ""
        If oRng(blankspace, 2).value() <> "" Then
            blankspace = blankspace + 1
        End If
    Loop

    Dim introw As Integer = 1
    Dim user As String
    Dim username As String = TextBox1.Text

    If username = "" Then
        MsgBox("Please Enter A User ID")
    Else
        Do
            user = oRng(introw, 2).value()


            If user = username Then


                oXL.ActiveWorkbook.Save()
                oXL.ActiveWorkbook.Close()

                Exit Do
            Else : introw = introw + 1

            End If
        Loop Until introw = blankspace

        oRng = Nothing
        oSheet = Nothing
        oXL.Quit()
        oXL = Nothing
        TextBox1.Clear()

1 个答案:

答案 0 :(得分:0)

以下示例删除第一列值等于零的行。修改它以满足您的需要。 你可以想象,删除一行“重新定位”下面的所有其他行,所以我发现向上工作更容易,而不是跟踪更改。

    For RowDelete = Worksheets(TargetSheet).UsedRange.Rows.Count To 1 Step -1

        If Cells(RowDelete, 1).Value = 0 Then
            Rows(RowDelete).Delete
        End If

    Next RowDelete

(如果运行速度太慢,请尝试ActiveSheet.EnableCalculation = False 和Application.ScreenUpdating = False之前,然后再次,但是在循环之后为True。)