选择在Excel宏中具有值的列(VBA中的范围对象)

如何在VBA中修改此行以仅选择具有值的列?

Set rng = Range("A1", Range("A65536").End(xlUp)).SpecialCells(xlCellTypeVisible)

我不认为我做错了,因为CountLarge属性有数十亿个单元

这是我的数据样本

最佳答案

@SiddharthRout Yes I only need the rows that have data. I think I have it working now with End(xlToLeft) from @JMax … Now that I’m iterating over the cells, I can just quit the For each loop once the last row is reached. I might have this working now. – makerofthings7 14 mins ago

  

为此,您既不需要.SpecialCells也不需要遍历各行:)

这是示例代码.这会将所有包含数据的行复制到Sheet2(已尝试并已测试)

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim LastRow As Long, LastCol As Long

    Set ws = Sheets("Sheet1")

    With ws
        LastRow = .Cells.Find(What:="*", After:=.Range("A1"), Lookat:=xlPart, _
        LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row

        LastCol = .Cells.Find(What:="*", After:=.Range("A1"), Lookat:=xlPart, _
        LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
        MatchCase:=False).Column

        With .Range("A1:" & Split(Cells(, LastCol).Address, "$")(1) & LastRow)
            .AutoFilter Field:=1, Criteria1:="<>"
            Set rng = ws.AutoFilter.Range
            rng.Offset(1, 0).Resize(rng.Rows.Count - 1).Copy _
            Destination:=Sheets("Sheet2").Range("A1")
        End With
    End With
End Sub

快照

我假设特定行中的所有单元格都将有数据,并且不会出现这样的情况

@makerofthings7: I think I know what exactly you are trying to do 🙂 you don’t need to use loops to achieve what you want. Just a quick question. Is it possible that say Cell C10 might have a value but B10 might not? – Siddharth Rout 12 mins ago

  

如果有的话,我们将不得不相应地设置自动过滤条件.

编辑:
方式2

另一种方法是对数据进行排序,将空格向下推,然后复制结果范围:)

HTH

转载注明原文:选择在Excel宏中具有值的列(VBA中的范围对象) - 代码日志