excel - 到达最后一个数据时逻辑中断
问题描述
点击按钮时,我想计算同一列中每一行中数据的冗余。它将对数据进行排序,并计算并显示该单词在该列中重复的次数。但是当它到达最后一个单词时,它不会计算并显示该单词有多少冗余。这是我的代码
Dim start As Integer
Dim last As Integer
Dim word As String
Dim line As Integer
Dim count As Integer
line = 5
count = 1
With Columns("A")
.Find(what:="*", after:=.Cells(1, 1), LookIn:=xlFormulas).Activate
start = ActiveCell.Row
last = ActiveCell.End(xlDown).Row
End With
Range(Cells(start, 1), Cells(last, 1)).Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
For i = start To last
word = Cells(i, 1).Value
Cells(line, 6) = word
For j = i + 1 To last
If Cells(j, 1).Value = word Then
count = count + 1
Else
Cells(line, 7) = count
line = line + 1
count = 1
End If
Exit For
Next j
Next i
我是vba的新手。请帮忙。提前致谢。
解决方案
逻辑缺陷在于Exit For
破坏了循环的目的
For j = i + 1 To last
If Cells(j, 1).Value = word Then
count = count + 1
Else
Cells(line, 7) = count
line = line + 1
count = 1
End If
Exit For '<--- this will always makes the loop exit after first iteration
Next j
因此您应该消除循环并仅对其第一次迭代运行检查
If Cells(i + 1, 1).Value = word Then
count = count + 1
Else
Cells(line, 7) = count
line = line + 1
count = 1
End If
推荐阅读
- c - 为什么 ioctl 在没有连接设备的情况下返回 0?
- codeigniter - codeigniter 4 使用户能够定义自己的路由
- javascript - SwiperJS:水平旋转木马,一张幻灯片展开
- c# - Auth0 + Asp.Net Core 2.1 + 禁止错误 403
- sql-server - 如何连接不同表中同名的列
- visual-studio-code - 是否可以有一个考虑我输入长度的片段?
- python - Python cachetools 统计和使用自定义键
- php - 访问多对多关系的集合并将集合的特定部分作为 old() 传递给更新视图
- laravel - 我可以使用 AppserviceProvider.php 在 view()->composer() 函数中设置文件夹吗?
- node.js - 打字稿不能返回,无论如何甚至不使用回调