excel - 为什么我的 vba 循环每次都跳到我的外部下一个?
问题描述
所以我有一个双循环,由于某种原因总是跳到我的外循环。循环来自:
For j = lastColumn To 6 Step (-1)
至:
Next i
每一次。但是,在我的数据集中,应该在我的 if 语句中捕获各种混合数据并计算数据。
有任何想法吗?也许我错误地格式化了宏。
Sub CheckDates()
Dim count As Integer
Dim i As Integer
Dim j As Integer
Sheets(1).Select
lastrow = ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row
'have to keep data in a table for this to actually work as it ctrls+left to the table, which will end where the very last text of any row is
lastColumn = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).Column
count = 0
i = 3
j = lastColumn
For i = 3 To lastrow
For j = lastColumn To 6 Step (-1)
If Sheet1.Cells(i, j) < Sheet2.Cells(1, 1) And Sheet1.Cells(i, j - 1) = "Reçu" Then
count = count + 1
GoTo NextIteration
End If
Next j
NextIteration:
Next i
Sheet2.Cells(1, 7) = count
Sheets(2).Select
'Runs the DeleteSAC Macro
Call DeleteSAC
End Sub
解决方案
简化
对行使用Long ,对列使用Integer。
当你写的时候With Sheet1
,你应该写的任何地方Sheet1
,例如Sheet1.Range(whatever)...
你可以写.Range(whatever)
,直到你用End With 结束。
Exit For仅退出它所在的For 循环。因此,它与您对Goto行所做的完全相同,但您正在使用更多行。
当您使用 Sheet1 或 Sheet2 等时,您实际上是在使用代码名称,因此您可以更改选项卡中的名称,代码仍将运行。
当您逐行删除时,通常使用向后计数,因此无需这样做,因为您只是在计数。
Option Explicit
Sub CheckDates()
Dim dataCount As Long
Dim i As Long
Dim j As Integer
Dim lastrow As Long
With Sheet1
lastrow = .Cells(.Rows.count, "B").End(xlUp).Row
'have to keep data in a table for this to actually work as it ctrls+left
'to the table, which will end where the very last text of any row is
lastColumn = .Cells(1, .Columns.count).End(xlToLeft).Column
For i = 3 To lastrow
For j = 6 To lastColumn
If .Cells(i, j) < Sheet2.Cells(1, 1) And .Cells(i, j - 1) = "Reçu" Then
dataCount = dataCount + 1
Exit For
End If
Next
Next
End With
With Sheet2
.Cells(1, 7) = dataCount
.Select
End With
'Runs the DeleteSAC Macro
DeleteSAC
End Sub
推荐阅读
- python - 如何使用 pandas 将我的 python 网络抓取数据导出到现有 excel 文件中的特定工作表?
- git - 如何在 GitHub 中使用 REST API 列出给定主题的所有存储库?
- binary - 将二进制文件转换为单词
- deezer - 登录 deezer 开发人员门户时出错
- javascript - wix 按钮重定向使用 wixlocation.to
- ios - UIView 在使用 UIPanGestureRecognizer 拖动时不会移动
- python - 每个产品的滞后销售
- c# - 当我有单独的“数据”和“程序”时,这些模式中哪一个是更好的 OOP 设计?
- amazon-web-services - 是否可以从 AWS EC2 实例设置本地 Kubernetes 开发环境(Minikube 等)?
- java - 无法将 Spring Boot Admin Server 2 和 Spring Boot Admin Client 2 与 Spring Boot 2 集成在单个应用程序中