excel 宏-删除工作簿中多个列上的空列(有标题)

3lxsmp7m  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(116)

我正在寻找一种方法来删除所有空白列(有标题)在一个工作簿内的多个文件夹。
我有一个代码(不是我写的),可以删除活动工作表中的所有空白列,这很好用。然而,我想让这个代码同时在多个工作表中工作。我找不到任何东西:

Sub DeleteBlankColumns()
Dim i As Long
    Dim lnglastcolumn As Long
    Dim delrng As Range
    
    With ActiveSheet
        lnglastcolumn = .Cells(1, Columns.Count).End(xlToLeft).Column
        
        For i = 1 To lnglastcolumn
            If .Cells(.Rows.Count, i).End(xlUp).row = 1 Then
                If delrng Is Nothing Then
                    Set delrng = .Columns(i)
                Else
                    Set delrng = Union(delrng, .Columns(i))
                End If
            End If
        Next i
    End With
    
    delrng.Delete
End Sub

字符串
任何帮助非常感谢!

ogsagwnx

ogsagwnx1#

Use Sheets对象:

Sub DeleteBlankColumns(curSheet As Object)
    Dim i As Long
    Dim lnglastcolumn As Long
    Dim delrng As Range
    
    With curSheet
        lnglastcolumn = .Cells(1, Columns.Count).End(xlToLeft).Column
        
        For i = 1 To lnglastcolumn
            If .Cells(.Rows.Count, i).End(xlUp).Row = 1 Then
                If delrng Is Nothing Then
                    Set delrng = .Columns(i)
                Else
                    Set delrng = Union(delrng, .Columns(i))
                End If
            End If
        Next i
    End With
    
    If Not (delrng Is Nothing) Then
        delrng.Delete
    End If
End Sub

Sub Run()
    DeleteBlankColumns Sheets("Sheet1")
    DeleteBlankColumns Sheets("Sheet2")
End Sub

字符串

pbwdgjma

pbwdgjma2#

请尝试下一个代码:

Sub DeleteEmptyColsInAllSheets()
 Dim wb As Workbook, sh As Worksheet, delRng As Range, lnglastcolumn As Long, i As Long
 Set wb = ActiveWorkbook ' use here the workbook you need

 For Each sh In wb.Worksheets
    With sh
        lnglastcolumn = .cells(1, Columns.count).End(xlToLeft).column
        
        For i = 1 To lnglastcolumn
            If .cells(.rows.count, i).End(xlUp).Row = 1 Then
                If delRng Is Nothing Then
                    Set delRng = .Columns(i)
                Else
                    Set delRng = Union(delRng, .Columns(i))
                End If
            End If
        Next i
    End With
    If Not delRng Is Nothing then
        delRng.Delete: Set delRng = Nothing
    End If
 Next sh
End Sub

字符串

相关问题