我不知道它什么时候退出我的 for 循环,我得到运行时错误 28

I can't figure out when it is now exiting my for loop and I get runtime error 28

我有以下功能来查找电子表格中包含数据的最后一列,但出现运行时错误 28。我相信它没有正确退出我的 for 循环。我错过了什么愚蠢的东西吗?我已经制作了多个简单的函数,完全像这样,没有任何问题。

Function max_column()

Dim i As Integer
Dim max_col As Integer

For i = 1 To 200
If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For
Next i
max_column() = max_col
Exit Function
End Function

我会稍微修改一下您的 If 声明。

Function max_column()

Dim i As Integer
Dim max_col As Integer

For i = 1 To 200
    If Worksheets("Sheet1").Cells(2, i) = "" Then 
    max_col = i
    Exit For
    Else
    End If
Next i

max_column() = max_col

End Function

希望对您有所帮助!

无需循环,只需使用 END()。

这将 return 第 2 行中的第一个空白单元格:

Function max_column() as Long
    If Worksheets("Sheet1").Cells(2, 1) = "" Then
        max_column = 1
    Else
        max_column = Worksheets("Sheet1").Cells(2, 1).End(xlToRight).Column + 1
    End If
End Function

如果您想要的是行中最后使用的单元格右侧的列,请使用:

Function max_column() as Long
    max_column = Worksheets("Sheet1").Cells(2, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column + 1
End Function

这里发生了一些事情。首先,您应该避免使用 Integers 而使用 Longs。为 Integer 分配一个大于 32,767 的值。如果您尝试给它一个值 32,768,您将得到 运行 次 Overflow 错误(错误编号 8)。

修复第一位看起来像这样:

Function max_column()

    Dim i As Long
    Dim max_col As Long

    For i = 1 To 200
    If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For
    Next i
    max_column() = max_col
    Exit Function
End Function

当然,这并不能解决问题,它只是消除了一个容易导致问题的常见错误。这里有几件更险恶的事情可能是问题所在。首先是您使用的是不合格的 Worksheets 引用,这意味着无论这是否是预期目标,您都依赖 ActiveWorkbook

第二个问题是:字符。这表示一个换行符,而不是实际的换行符!多么方便...除了你错过了你的逻辑问题。

For i = 1 To 200
    If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For
Next i

真的是:

For i = 1 To 200
    If Worksheets("Sheet1").Cells(2, i) = "" Then 
        max_col = i
    End If

    Exit For
Next i

这个循环将永远做的是 return 1 或 0,因为第二行中的第一个单元格为空,或者循环退出。

最后,您的函数 return 调用再次被调用,这就是造成堆栈溢出错误的原因(因为它一直在调用和调用...)。

将其固定为 max_colum,它实际上应该是 GetTheFirstColumnOnTheActiveSheetThatHasANullStringValueInTheSecondRow(请注意,实际功能与简单的 max_column 不同)。

进行这些更改后,您的代码将变为:

Function max_column()
    Dim i As Long
    Dim max_col As Long

    For i = 1 To 200
        If Worksheets("Sheet1").Cells(2, i) = "" Then 
            max_col = i
            Exit For
        End If
    Next i

    max_column = max_col

    Exit Function
End Function

并进行最终调整以避免其他错误:

Public Function GetMaxColumn() as Long
    Dim i As Long
    For i = 1 To 200
        If ActiveWorkbook.Worksheets("Sheet1").Cells(2, i) = vbNullString Then 
            GetMaxColumn = i
            Exit Function
        End If
    Next i
End Function

瞧!一个完美的函数。