首页 > 解决方案 > 如何在整个数据中重复代码?

问题描述

我已经编写了几行代码,它们也像我想要的那样工作,但我不知道如何在我的所有数据行中重复它。这似乎是一件相当简单的事情,但自从我几天前开始使用 VBA 以来,我一直在为这行代码而苦恼

如果我ActiveCell.Offset(-1,-4)在我的代码之后继续,这是一个错误,我不知道如何在所有行中重复代码。

Sub SelectRowsWithNoBlanks()
    Range("A2").Select
    
    If ActiveCell.Offset(0, 0).Value <> "" And ActiveCell.Offset(0, 1) <> "" And ActiveCell(0, 1) <> "" And ActiveCell(0, 1) <> "" Then
        Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 4)).Select
    End If
End Sub

标签: excelvba

解决方案


@SiddharthRout 因为我无权访问数据,但我不知道。但我认为以后为更多列扩展代码不会有问题。因此,在我现在编写的代码中,我正在检查 AD 列,但我认为如果需要,我可以轻松地为更多列添加“检查” – Anna von Blohn 43 秒前

在这种情况下,这是一个示例代码。

逻辑

  1. 正如@Pᴇʜ 提到的,避免使用.Select. 处理对象。
  2. 找到最后一行并遍历行。要找到您可能希望看到的最后一个
  3. 一种方法(我正在使用)是计算使用Application.WorksheetFunction.CountA. 因此,如果它是列AD则应该填充 4 个单元格以将“行”视为已填充。同样,对于 Cols A 到 E,应该有 5 个单元格要填充,以将“行”视为已填充,依此类推。

代码

我已经评论了代码。因此,如果您在理解它时遇到问题,请告诉我。

Option Explicit

Sub SelectRowsWithNoBlanks()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long
    Dim myRange As Range, rng As Range
    
    '~~> Change this to the relevant sheet
    Set ws = Sheet1
    
    With ws
        '~~> Find the last row in Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        '~~> Loop through the rows
        For i = 2 To lRow
            '~~> Change this as applicable
            Set rng = .Range("A" & i & ":D" & i)
            
            '~~> Check if the range is completely filled
            If Application.WorksheetFunction.CountA(rng) = rng.Columns.Count Then
                '~~> Store the range in a range object
                If myRange Is Nothing Then
                    Set myRange = rng
                Else
                    Set myRange = Union(myRange, rng)
                End If
            End If
        Next i
    End With
    
    'If Not myRange Is Nothing Then Debug.Print myRange.Address
    
    '~~> Check if any filled rows were found
    If Not myRange Is Nothing Then
        With myRange
            '
            '~~> Do what you want with the range
            '
        End With
    Else
        MsgBox "No filled rows were found"
    End If
End Sub

推荐阅读