如果行数小于一定数量,使用 vba Excel 删除列

问题描述 投票:0回答:1

我有一个包含很多列的 Excel 文件。我想使用 vba 创建一个循环 (B1:LastCol),该循环遍历填充列的数量,并删除包含少于一定行数的列(例如,少于 50 行的列将被删除为它们是不完整的测量)。 我不知道我该如何处理这个问题。我添加了一些损坏的代码,以便更好地了解我想要的内容。

Sub test()
 Dim LastColNr As Long
 Dim LastCol As String
 LastColNr = Graphs.Cells(1, Columns.Count).End(xlToLeft).Column
 LastCol = GetColumnLetter(LastColNr)
 
 MsgBox "Column Count: " & LastColNr  & LastCol
 
 Dim cel As Range
 Dim rng As Range
 
 For Each rng In Range("B1: LastCol").Columns
     If rng("B1", rng("B1").End(xlDown)).Rows.Count > 50
       Column.Delete
     End If
 Next rng
End Sub
excel vba loops range row
1个回答
0
投票

也许是这样的:

Sub Test()

    With Graphs

        Dim LastCol As Long
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        
        'As we're deleting columns we need to step backwards.
        'Deleting column A would make column B become column A and then get missed on the next loop iteration.
        Dim x As Long
        Dim LastRow As Long
        For x = LastCol To 1 Step -1
            LastRow = .Cells(.Rows.Count, x).End(xlUp).Row
            
            If LastRow < 50 Then
                .Cells(1, x).EntireColumn.Delete Shift:=xlToLeft
            End If
        
        Next x
    
    End With

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.