excel - 如何在整个数据中重复代码?
问题描述
我已经编写了几行代码,它们也像我想要的那样工作,但我不知道如何在我的所有数据行中重复它。这似乎是一件相当简单的事情,但自从我几天前开始使用 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
解决方案
@SiddharthRout 因为我无权访问数据,但我不知道。但我认为以后为更多列扩展代码不会有问题。因此,在我现在编写的代码中,我正在检查 AD 列,但我认为如果需要,我可以轻松地为更多列添加“检查” – Anna von Blohn 43 秒前
在这种情况下,这是一个示例代码。
逻辑
- 正如@Pᴇʜ 提到的,避免使用
.Select
. 处理对象。 - 找到最后一行并遍历行。要找到您可能希望看到的最后一个
- 一种方法(我正在使用)是计算使用
Application.WorksheetFunction.CountA
. 因此,如果它是列A
,D
则应该填充 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
推荐阅读
- windows-10 - 运行 npm run dist 后 dist 文件夹被锁定
- spring-boot - 如何为 Camel JMS 应用程序实现 CRL 和 OCSP?
- angular - 如何将 Firebase 实时数据库连接到我的 Angular 7 应用程序?使用 CRUD 操作
- xml - 错误:“(”需要启动 ATTLIST 枚举
- android - 检测导航组件中的弹出
- ios - 退格不能在 swift 的正则表达式之外工作
- amazon-web-services - 如何从另一个 AWS 账户访问公共 S3 存储桶?
- c# - 如何组合 Swashbuckle 过滤器?
- swift - 如何解决 UIImageView 连接到 Swift4?
- amazon-web-services - Route53 Healthcheck 使用 Terraform 与 Cloudwatch 警报集成