如何使用用户表单删除数据时删除行中的空单元格

时间:2015-09-17 03:09:47

标签: vba excel-vba userform excel

嗨,目前我有一个用户表单,允许我根据项目ID的用户输入删除所选行,它将删除该项目ID的整行。但是,删除数据时,不会删除空行并保持为空。因此,我必须在使用删除命令按钮删除行中的数据后自己手动删除空行。是否有任何其他代码我必须添加到我当前的代码中,以便在该特定行中删除数据后,空行也将自动删除? 下面是我的删除命令按钮的代码。

Private Sub CommandDeleteButton1_Click()

    Dim lastrow
    Dim ProjCode As String
    Dim LabelProjName As String
    Dim LabelObjective As String
    Dim LabelProjSponsor As String
    Dim LabelProjSponsorNew As String
    Dim LabelProjManager As String
    Dim LabelRegulatory As String
    Dim LabelRiskLvl As String
    Dim LabelDatePar As Date
    Dim LabelCostPar As Long
    Dim LabelAffectCust As String
    Dim LabelCustNonRetail As String
    Dim LabelCustRetail As String
    Dim LabOutsourcingImp As String
    Dim LabelKeyUpdate As String
    Dim LabelSector As String

         lastrow = Sheets("Program Status Summary").Range("B" & Rows.Count).End(xlUp).row
         ProjCode = TextBoxProjCode.Text

            For currentrow = 4 To 100
                If Cells(currentrow, 2).Text = ProjCode Then
                    Cells(currentrow, 2).EntireRow.ClearContents
                End If

    Next currentrow

TextBoxProjCode.SetFocus

End Sub

非常感谢任何帮助。谢谢:))

2 个答案:

答案 0 :(得分:1)

尝试使用此代码在Next currentrow

之后插入它
With ws.Range("B2:B" & LastRow)
    If WorksheetFunction.CountBlank(.Cells) > 0 Then
        .SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End If
End With

抱歉,我误解了你的问题。要删除空行,请尝试修改下面给出的标准代码,用于删除空行。

Sub DeleteRows()
  Dim ws As Excel.Worksheet
  Dim LastRow As Long
  Set ws = ActiveSheet
  LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
   With ws.Range("A2:A" & LastRow)
    If WorksheetFunction.CountBlank(.Cells) > 0 Then
        .SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End If
   End With
End Sub

请确保在测试代码中尝试删除之前复制数据。

答案 1 :(得分:1)

我优化了您发布的代码并将.EntireRow.ClearContents更改为.EntireRow.Delete

Option Explicit

Private Sub CommandDeleteButton1_Click()
    Const CL As String = "B"
    Dim fRow As Long, lRow As Long, fnd As Variant, v As Variant, prjCode As String

    fRow = 4
    With Worksheets("Program Status Summary")

        lRow = .Range(CL & .Rows.Count).End(xlUp).Row
        prjCode = Val(TextBoxProjCode.Text)

        v = Application.Transpose(.Range(CL & fRow & ":" & CL & lRow))
        fnd = Application.Match(prjCode, Split(Join(v, ","), ","), 0)

        If Not IsError(fnd) Then .Cells(fnd + fRow - 1, 2).EntireRow.Delete '<-----

    End With
    TextBoxProjCode.SetFocus
End Sub