Excel VBA:适用于长距离的每个循环

我在Excel工作簿中使用了几个VBA For Each循环,出于某种原因,在循环达到32,766行后,出现运行时错误。 我想这是一个Int / Longtypes的错误,但我似乎无法弄清楚如何解决它。 这是我现在的代码:

' Add Play Call hyperlinks Dim Rng As Range, Cell As Range Dim FileName As String Dim Bureau As String Dim CopiedFilesDirectory As String Dim AudioFilePath As String lastRow = Sheets("CallLog").Range("I" & Rows.Count).End(xlUp).Row Set Rng = Sheets("CallLog").Range("I" & firstRow & ":I" & lastRow) For Each Cell In Rng FileName = Range("I" & Cell.Row).Value MatterNumber = Replace(Range("K" & Cell.Row).Value, "/", "-") ContactUsername = Range("M" & Cell.Row).Value Bureau = Range("N" & Cell.Row).Value CopiedFilesDirectory = ImportCallsUserForm.CopyFilesDirectoryTextBox.Value AudioFilePath = CopiedFilesDirectory & Bureau & "\" & ContactUsername & "\" & MatterNumber & "\" & FileName & ".flac" With Worksheets("CallLog") .Hyperlinks.Add Anchor:=.Range("S" & Cell.Row), _ Address:=AudioFilePath, _ ScreenTip:="Click to play call", _ TextToDisplay:="Play Call" .Hyperlinks.Add Anchor:=.Range("T" & Cell.Row), _ Address:="", _ ScreenTip:="Click to write a summary", _ TextToDisplay:="Write Call Summary" End With Next Cell 

由于我正在使用范围,我认为也许有一个特殊types的variables对Int范围与长范围,但我没有find任何东西后,进行广泛的在线调查。

任何帮助总是赞赏,我很乐意澄清任何不清楚的事情。

你面对的问题与Range无关,或者迭代它。 这是由于您可以添加到工作表中的超链接字段的数量的限制。 限制在65530左右。由于每次迭代添加两个超链接,因此您最多只能在32766。

你可以通过让一个worksheet_click事件触发一些使用target.range的代码来dynamic创build一个URL,像这个循环所做的那样,并在那里发送用户。 这不是一个很好的解决方法,但是鉴于Excel的限制,这是最好的。

您还没有在任何地方声明firstRowlastRow 。 这些可能会被首次使用时被解释为整型variables。

声明这些明确的Long ,你应该没事的。

在每个模块的顶部也使用Option Explicit是一个好主意 – 这迫使你显式声明所有的variables,所以这种types的错误不会发生。