简体   繁体   中英

Error handling for merging cells in Excel VBA

I'm currently developing an add-in for Excel which will automatically format a table. The users has to follow the specific format when preparing the table, or else the common error of "Merging cells only keeps the upper-left cell value, and discards the other values." is bound to appear.

I would like to mute this alert from Excel, but would still like to catch this error and pass a different message to the users to terminate this sub. I've tried this:

Sub FormatTable()
    On Error Goto ErrHandler
    Application.DisplayAlerts = False
    'Codes for formatting the table
    Exit Sub
ErrHandler:
    MsgBox "Incorrect formatting. Terminating process to conserve data."
End Sub

However, I do realise that using "Application.DisplayAlerts = False" will cause Excel to choose the default action and proceed to merge the cells which causes a big mess. It will not go the ErrHandler. Is there some way for making this happen? Thank you.

You could test for merged cells in the selected range prior to running your code:

Public Function HasMergedCells(oRng As Range)
    Dim oCell As Range
    Dim oArea As Range
    For Each oArea In oRng.Areas
        For Each oCell In oArea.Cells
            If oCell.MergeArea.MergeCells Then
                HasMergedCells = True
                Exit Function
            End If
        Next
    Next
End Function

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