VBA For循环误取范围外行首数据且遗漏末行问题求助
问题原因与修复方案
核心问题分析
- VBA里单元格索引是从1开始的,代码中
Row.Cells(0)会自动指向当前行的上一行单元格,这就是明明选的是B2起始范围,却取到B1值的原因。 Else: Exit For会在遇到第一个空单元格时直接终止循环,导致最后一行有效数据被遗漏(只要最后一行后是空行,就会触发退出)。- 用
i手动计数匹配OtherRangeOfInterest.Rows(i),逻辑依赖无空行的连续数据,一旦有跳过就会出现数据错位。
修复后的代码
' 避免Activate,直接引用工作表更稳定 Dim ws1 As Worksheet, ws2 As Worksheet Set ws1 = ThisWorkbook.Sheets("Sheet1") Set ws2 = ThisWorkbook.Sheets("Sheet2") Dim RangeOfInterest As Range Set RangeOfInterest = ws1.Range(ws1.Range("B2"), ws1.Range("B2").End(xlDown)) ' 按逻辑定义对应D2起始的范围 Dim OtherRangeOfInterest As Range Set OtherRangeOfInterest = ws2.Range(ws2.Range("D2"), ws2.Range("D2").End(xlDown)) Dim dict As Object Set dict = CreateObject("scripting.dictionary") Dim currentRow As Range Dim rowIndex As Long rowIndex = 1 For Each currentRow In RangeOfInterest.Rows ' 用Cells(1)获取当前行的B列单元格 If Not IsEmpty(currentRow.Cells(1).Value) Then ' 防止索引越界 If rowIndex <= OtherRangeOfInterest.Rows.Count Then dict(currentRow.Cells(1).Value) = OtherRangeOfInterest.Rows(rowIndex).Cells(1).Value rowIndex = rowIndex + 1 End If ' 移除Exit For,遇到空行直接跳过而非终止循环 End If Next currentRow
额外优化建议
- 尽量不用
Activate/Select,直接通过工作表对象引用范围,减少代码出错概率。 - 如果需要处理非连续空行,保留空行跳过逻辑即可,不要终止循环。
- 可以添加范围有效性检查,比如判断
RangeOfInterest是否为空,避免B2本身为空时的报错。
内容的提问来源于stack exchange,提问作者DIS
相关产品推荐
相关产品推荐

