简体   繁体   中英

VBA Excel - Resolving Error 13 when deleting text from a field

Have a spreadsheet I am editing for a project at work. The sheet uses string values in col 1, 3, 4, and 5. Multiple people will be accessing this sheet so in order to maintain a clean appearance I have set the sheet to capitalize the values in each of those columns upon entry.

    Dim letter as String
    Select Case Target.Column
        Case Is = 1, 3, 4, 5
            Application.EnableEvents = False
            letter = Target.Value
            letter = UCase(letter)
            Target.Value = letter
    End Select
    Application.EnableEvents = True

This works great except for when you drag and select multiple fields to delete. It returns run-time error 13 and I know it is from the letter string becoming " " and the program can't capitalize a blank string.

I can't wrap my brain around how to bypass this Select if the letter string is blank. I've spent some considerable time looking for the answer but can't seem to find something that applies to this situation. Any input is appreciated. Thank you

Try an if statement to test for an empty string

Dim letter as String
Select Case Target.Column
    Case Is = 1, 3, 4, 5
        Application.EnableEvents = False
        letter = Target.Value

        If Len(letter) > 0 then
             letter = UCase(letter)
             Target.Value = letter
        Else
             Target.Value = letter
        End IF
End Select
Application.EnableEvents = True

As I mentioned in my comment, your problem is not in the UCase line.

Try this:

Dim letter as String
Dim cell As Variant

Application.EnableEvents = False 
For each cell in Target
    Select Case cell.column
        Case Is = 1, 3, 4, 5
             Cell.Value = UCase(Cell.Value)
    End Select
Next cell

Application.EnableEvents = True

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