简体   繁体   中英

Excel VBA - Overflow error on Range select

I am having an error when I try to select cells from a sheet:

  Dim ABHdataPath As String
  Dim ABHdataFile As Excel.Workbook

  ABHdataFile.Sheets("Booked").Activate ' make sure program starts from correct sheet
        ColumnName = ColumnLetter(ABHdataFile.Sheets("Booked").Cells(5, Columns.Count).End(xlToLeft).Column)
        ABHbooked = ABHdataFile.Sheets("Booked").Range("B5:" & ColumnName & Cells(Rows.Count, "B").End(xlUp).row).Value

When running above line, I get this error:

在此处输入图片说明

It doesn't give me any option to debug the code, so I find it hard to locate the error.

EDIT I have been able to debug my code, this is where it ends:

ABHBooked = ABHdataFile.Sheets("Booked").Range("B5:" & ColumnName & Cells(Rows.Count, "B").End(xlUp).row).Value

Debug:

ABHBooked = Empty

Rows.Count = 1048576

xlUp = -4162

ColumnName = CD

The function gives error whenever the ColumnNumber is less than 1. Thus, introduce a small check and it should work:

Function ColumnLetter(ColumnNumber As Long) As String
    Dim n As Long
    Dim c As Byte
    Dim s As String

    If ColumnNumber < 1 Then
        ColumnLetter = "NAN"
        Exit Function
    End If

    n = ColumnNumber
    Do
        c = ((n - 1) Mod 26)
        s = Chr(c + 65) & s
        n = (n - c) \ 26
    Loop While n > 0
    ColumnLetter = s

End Function

The problem was not that my variable wasn't stored as long , but rather the format of my selection.

This fixed the issue:

Selection.NumberFormat = "General”

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