如果特定列名称下的单元格为空,如何删除整行的空白?

时间:2019-07-04 07:24:57

标签: excel xml vba delete-row

我需要将多个xml文件导入Excel,并且需要对齐粘贴在Excel中的所有xml表的列名。问题是某些xml文件还包含一列,我不需要。该列会在表格的中间弹出,因此很难处理数据。此外,如果名称为“ content”的单元格为空,则需要删除整行。

到目前为止,我已经设法制作了一个命令按钮,该按钮将xml文件导入到Excel中(参见代码)。

Sub CommandButton1_Click()    
    Dim xWb As Workbook
    Dim xSWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    Set xSWb = ThisWorkbook
    xCount = 1
    xFile = Dir(xStrPath & "\*.xml")
    Do While xFile <> ""
        Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
        xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
        xWb.Close False
        xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
        xFile = Dir()
    Loop
    Application.ScreenUpdating = True
    xSWb.Save
    Exit Sub

ErrHandler:
    MsgBox "no files xml", , "Kutools for Excel"
End Sub

我希望从30个xml文件中获得30个表,并且在同一列中具有相似的标题。此外,由于数据集有些庞大,因此我需要删除我引用的空白单元格。

2 个答案:

答案 0 :(得分:0)

仅在您知道此列的标题名称的情况下,才尝试使用打开的工作簿的标题行中的Instr()寻找该附加列。在xWb工作簿中执行此操作,并在更正后将粘贴复制到您的主工作簿中。 关于删除空单元格操作,您可以在粘贴到主文件后执行此操作。只需执行简单的if()指令,即可检查指定列中的单元格是否为空-“”(双引号)。 您可以将此if()从2循环到最后一行-最后一行您可以使用xWb.cells(rows.count,1).end(xlup).Row在xWb中“测量”。如果你做任何事,给我个手势。

答案 1 :(得分:0)

这可以帮助您:

Option Explicit

Sub test()

    Dim ColumnName As String
    Dim LastColumn As Long, LastRow As Long
    Dim rngFoundContent As Range
    Dim rngFoundColumn As Range

    'Change sheet name if needed
    With ThisWorkbook.Worksheets("Sheet1")

        'Search for the word "Content"
        Set rngFoundContent = .UsedRange.Find("Content", LookIn:=xlValues)
        'If "Content" found
        If Not rngFoundContent Is Nothing Then
            'Delete the row below
            .Rows(rngFoundContent.Row + 1).EntireRow.Delete
        End If

        'Search for the Column Name (Lest us assume that column name is "Test"0
        ColumnName = "Test"
        'Let us assume that Headers appear in row 1, find the last column of row 1
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        'Search for the word column Test
        Set rngFoundColumn = .Range(.Cells(1, 1), .Cells(1, LastColumn)).Find(ColumnName, LookIn:=xlValues)
        'If column found
        If Not rngFoundColumn Is Nothing Then
            'Delete whole column
            .Columns(rngFoundColumn.Column).EntireColumn.Delete
        End If

    End With

End Sub