2017-10-20 42 views
0

我有以下功能找到电子表格中有数据的最后一列,我得到一个运行时错误28.我相信它并没有正常退出我的for循环。我错过了一些愚蠢的东西吗?我已经完成了多个简单的功能,完全没有问题。我不知道它现在退出我的for循环,我得到运行时错误28

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 
+0

从'if'语句中删除'max_col = i:'(注意冒号也被删除)...将第3行从结尾更改为'max_column()= i' ....删除'Exit Function' .. 。删除'Dim max_col As Integer' – jsotola

回答

1

有这里发生了一些事情。首先,你应该避免使用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 

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

最后,你的函数返回调用再次被调用,这是造成堆栈溢出错误(因为它保持调用和调用和调用....)。

修复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 

瞧!一个完美的功能函数。

+0

非常有意义。我有非常不好的习惯,我需要打破。 – user3865990

0

我会稍微修改您的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 

希望这有助于!

+0

谢谢!我现在看到我的退出语句实际上并不在我的循环中。 – user3865990

1

不需要循环,只需使用END()。

这将在第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 
+0

如果'Cells(2,1)'的值是'vbNullString',那么End命令的工作方式与OP的功能不同。 –

+0

@BrandonBarney true,fixed。请参阅编辑。 –

+0

@BrandonBarney仍然不需要循环。 –

相关问题