簡體   English   中英

在Excel VBA中合並單元格的錯誤處理

[英]Error handling for merging cells in Excel VBA

我目前正在開發一個Excel加載項,它將自動格式化表格。 用戶在准備表時必須遵循特定的格式,否則常見的錯誤是“合並單元格僅保留左上角的單元格值,而丟棄其他值”。 必然會出現。

我想從Excel中忽略此警報,但仍想捕獲此錯誤,並將其他消息傳遞給用戶以終止此子項。 我已經試過了:

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

但是,我的確意識到使用“ Application.DisplayAlerts = False”將導致Excel選擇默認操作並繼續合並單元格,這會造成很大的混亂。 它不會去ErrHandler。 有什么辦法可以做到這一點? 謝謝。

您可以在運行代碼之前測試所選范圍內的合並單元格:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM