简体   繁体   English

删除带有空白标题的列 VBA

[英]Delete Columns With Blank Headers VBA

I am looking for assistance in deleting two columns within my range of data that have blank headers.我正在寻求帮助以删除我的数据范围内具有空白标题的两列。 These blank headers will appear in the first row of my used range.这些空白标题将出现在我使用的范围的第一行。 What would be the best way to go about this? go 关于这个问题的最佳方法是什么? Should I use.Find to search for blank cells in the first row and then get the column address of the two blank cells in order to delete them?我应该使用.Find 搜索第一行中的空白单元格,然后获取两个空白单元格的列地址以删除它们吗?

Currently, I am just deleting the columns that I know they'll appear in, but this has the potential to change.目前,我只是删除我知道它们会出现的列,但这有可能改变。 Current code:当前代码:

rngUsed.Columns("F").Delete
rngUsed.Columns("H").Delete

Because the data can change, what would be the better way of handling this?由于数据可能会发生变化,那么更好的处理方法是什么?

Thanks!谢谢!

You can use SpecialCells to find the blanks in the first row and remove the corresponding columns:您可以使用SpecialCells查找第一行中的空白并删除相应的列:

Dim rng As Range

Set rng = Range("B3").CurrentRegion 'for example...

On Error Resume Next 'ignore error if no blanks
rng.Rows(1).SpecialCells(xlCellTypeBlanks).EntireColumn.Delete
On Error GoTo 0 'stop ignoring errors

Delete Columns With Blank Headers删除带有空白标题的列

  • The current setup is in Test Mode ie it will select the columns to be deleted.当前设置处于Test Mode ,即它将 select 要删除的列。 If the result is satisfactory, switch to Const TestMode As Boolean = False when the columns will be deleted.如果结果令人满意,则在删除列时切换到Const TestMode As Boolean = False
  • Adjust the values in the constant sections.调整常数部分中的值。

The Code编码

Option Explicit

Sub TESTdeleteBlankHeadered()
    
    Const wsName As String = "Sheet1"
    Const ColumnsCount As Long = 2 ' -1 - all columns containing blank headers.
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    
    Dim rg As Range: Set rg = wb.Worksheets(wsName).UsedRange
    
    deleteBlankHeadered rg, ColumnsCount ' first found columns
    'deleteBlankHeadered rg, ColumnsCount, True ' last found columns
    'deleteBlankHeadered rg ' all found columns

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      In a worksheet, deletes a specified number of its columns,
'               defined by blank cells in the first (header) row of
'               a given range.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub deleteBlankHeadered( _
        rg As Range, _
        Optional ByVal ColumnsCount As Long = -1, _
        Optional ByVal LastOccurringColumns As Boolean = False)
        
    ' When 'True', tests with select.
    ' When 'False', deletes.
    Const TestMode As Boolean = True
        
    ' Validate inputs.
    If rg Is Nothing Then Exit Sub
    If ColumnsCount < -1 Or ColumnsCount = 0 Then Exit Sub
    
    ' Define Source Row Range.
    Dim srg As Range: Set srg = rg.Areas(1).Rows(1)
    
    ' Write values from Source Row Range to Data Array.
    Dim cCount As Long: cCount = srg.Columns.Count
    Dim Data As Variant
    If cCount > 1 Then
        Data = srg.Value
    Else
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = srg.Value
    End If
    
    ' Define 'elements' of the 'For...Next' Loop.
    Dim cFirst As Long, cLast As Long, cStep As Long
    If LastOccurringColumns Then
        cFirst = cCount: cLast = 1: cStep = -1
    Else
        cFirst = 1: cLast = cCount: cStep = 1
    End If
    
    ' Declare additional variables.
    Dim drg As Range ' Delete Range
    Dim oCount As Long ' Occurrences Count
    Dim j As Long ' Data Array (Source Row Range) Columns Counter
    
    ' Loop through columns of Data Array and use found blank values
    ' to combine blank cells with Delete Range.
    For j = cFirst To cLast Step cStep
        If Not IsError(Data(1, j)) Then
            If Len(Data(1, j)) = 0 Then
                oCount = oCount + 1
                Select Case oCount
                    Case 1
                        Set drg = srg.Cells(j)
                        If ColumnsCount = 1 Then
                            Exit For
                        End If
                    Case ColumnsCount
                        Set drg = Union(drg, srg.Cells(j))
                        Exit For
                    Case Else
                        Set drg = Union(drg, srg.Cells(j))
                End Select
            End If
        End If
    Next
    
    ' Declare additional variables.
    Dim ActionTaken As Boolean
    
    ' Delete Column Ranges (containing blank headers).
    If Not drg Is Nothing Then
        Application.ScreenUpdating = False
        If TestMode Then
            drg.Worksheet.Activate
            drg.EntireColumn.Select
        Else
            drg.EntireColumn.Delete
        End If
        Application.ScreenUpdating = True
        ActionTaken = True
    End If
    
    ' Inform user.
    If ActionTaken Then
        MsgBox "Columns deleted: " & oCount, vbInformation, "Success"
    Else
        MsgBox "No columns deleted.", vbExclamation, "No Action Taken"
    End If

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM