You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel宏嵌套For循环编译错误:Next without For

解决Excel宏"Compile error: Next without For"错误

错误原因

你的代码中内层If InStr(1, Cells(j, "B").Value, "find me", vbTextCompare) > 0 Then语句缺少对应的End If,导致编译器无法正确识别Next j对应的循环结构,从而抛出编译错误。另外变量i未声明,建议补充声明避免隐式类型问题。

修复后的代码

Dim lastrow As Long
Dim firstrow As Long
Dim RowCount As Long
Dim lastrow1 As Long
Dim j As Integer
Dim i As Long ' 补充声明变量i

lastrow = Cells(Rows.Count, "B").End(xlUp).Row

For i = 1 To lastrow
    If Cells(i, "A").Value = "test" Then
        firstrow = i
        RowCount = i + 1
        
        Do Until Cells(RowCount, "A").Value = "test"
            RowCount = RowCount + 1
        Loop
        
        lastrow1 = RowCount - 1
        
        For j = i To lastrow1
            If InStr(1, Cells(j, "B").Value, "find me", vbTextCompare) > 0 Then
                Cells(i, "M").Value = Cells(j, "B").Value
            End If ' 补充缺失的End If
        Next j
    End If
Next i

额外说明

  • 补充End If后,For j循环的结构完整,编译器能正确匹配Next j
  • 声明i为Long类型,避免当行数超过Integer上限(32767)时出现溢出错误

内容的提问来源于stack exchange,提问作者user8421

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:12:05