简体   繁体   中英

Excel VBA: For Each loop for Long Range

I'm working with a few VBA For Each loops in my Excel workbook, and for some reason I get a run-time error after my loop reaches the 32,766 row. I figured this was an Int/Long type error, but I can't seem to figure out how to fix it. Here's my current code:

' 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

Since I'm working with ranges, I thought that maybe there was a special type of variable for Int Ranges vs. Long Ranges, but I couldn't find anything after doing extensive online research.

Any assistance is always appreciated, and I'm happy to help clarify anything that isn't clear.

The problem you are facing has nothing to do with the Range or iterating through it. It's due to the limitations of the number of Hyperlink fields you can add into a worksheet. The limitation is around 65530. Since you add two hyperlinks per iteration, you are maxing out at 32766.

You could work around this by having a worksheet_click event fire some code that uses the target.range to dynamically create a URL, like this loop is doing, and send the user there. That's not a great workaround, but it's the best you can do given the limitations of Excel.

You haven't declared firstRow or lastRow anywhere. These will likely be interpreted as Integer Variants when they are first used.

Declare these explicitly as Long , and you should be fine.

It's a good idea to also use Option Explicit at the top of every module - this forces you to explicitly declare all variables, so errors of this type cannot occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM