You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配Excel与LibreOffice的下划线单元格求和宏报错修复请求

修复兼容Excel与LibreOffice的下划线单元格求和宏

原代码在LibreOffice中报错「数据类型不匹配」,核心原因是两者对字体下划线的返回值类型逻辑不同:Excel的Font.Underline返回布尔值,而LibreOffice返回枚举常量(如com.sun.star.awt.FontUnderline.SINGLE),直接判断会触发类型错误。以下是修复后的跨平台兼容代码:

Option VBASupport 1
Option Compatible

Function SumUnderline(Optional WorkRng As Range = Nothing) As Double
    Dim Rng As Range
    Dim xSum As Double
    Dim isLibreOffice As Boolean
    
    ' 判断当前运行环境
    isLibreOffice = Not IsError(Application.Run("com.sun.star.awt.FontUnderline.NONE"))
    
    ' 未传入参数时,默认使用当前选中区域
    If WorkRng Is Nothing Then
        Set WorkRng = Selection
    End If
    
    For Each Rng In WorkRng
        Dim hasUnderline As Boolean
        ' 分别适配Excel和LibreOffice的下划线判断逻辑
        If isLibreOffice Then
            hasUnderline = (Rng.Font.Underline <> com.sun.star.awt.FontUnderline.NONE)
        Else
            hasUnderline = Rng.Font.Underline
        End If
        
        ' 仅对数值类型单元格求和,避免文本单元格报错
        If hasUnderline And IsNumeric(Rng.Value) Then
            xSum = xSum + CDbl(Rng.Value)
        End If
    Next
    
    SumUnderline = xSum
End Function

关键修改说明

  • 可选参数适配:LibreOffice要求可选参数必须指定默认值,因此调整为Optional WorkRng As Range = Nothing,并补充未传参时默认使用选中区域的逻辑。
  • 跨环境下划线判断:通过检测LibreOffice专属枚举常量的可用性区分环境,分别采用对应逻辑判断单元格是否带有下划线。
  • 数值校验:增加IsNumeric判断,避免非数值单元格参与求和引发错误。

使用方法

在单元格中输入公式:

  • 指定目标区域求和:=SumUnderline(A1:C10)
  • 对当前选中区域求和:=SumUnderline()

内容的提问来源于stack exchange,提问作者Oleksa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:27:07