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

如何在Excel中间列的每行中找出最长文本?支持公式或VBA

解决方案:找出每行排除指定列后的最长文本

一、公式法(适用于Excel 365/2021及以上版本)

直接在黄色列的第一个单元格输入以下公式,下拉填充即可:

=LET(
    row_data, INDIRECT("R"&ROW()&"C1:R"&ROW()&"C"&COLUMNS($1:$1), FALSE),
    exclude_cols, CHOOSECOLS(row_data, 1, COLUMN()),
    filtered_data, FILTER(row_data, NOT(ISNUMBER(XMATCH(COLUMN(row_data), COLUMN(exclude_cols))))),
    max_length, MAX(LEN(filtered_data)),
    INDEX(filtered_data, MATCH(max_length, LEN(filtered_data), 0))
)

公式说明:

  • row_data:提取当前行的所有数据,避免整行引用导致循环
  • exclude_cols:指定要排除的列——最左侧第1列,以及当前黄色单元格所在列
  • filtered_data:筛选出当前行中不属于排除列的所有单元格内容
  • max_length:计算筛选后文本的最大长度
  • INDEX+MATCH:定位并返回最长的文本(若有多个相同长度,返回第一个出现的)

二、VBA批量处理法(兼容所有Excel版本)

如果使用旧版Excel,或者需要一次性批量处理,可运行以下宏代码:

Sub GetLongestText()
    Dim targetCol As Integer
    Dim lastRow As Long, lastCol As Long
    Dim curRow As Long, col As Integer
    Dim maxLen As Integer, longestTxt As String
    
    ' 获取黄色列的列号(选中黄色列任意单元格后运行)
    targetCol = Selection.Column
    lastRow = Cells(Rows.Count, targetCol).End(xlUp).Row
    
    For curRow = 1 To lastRow
        maxLen = 0
        longestTxt = ""
        lastCol = Cells(curRow, Columns.Count).End(xlToLeft).Column
        
        ' 遍历当前行,跳过第1列和目标列
        For col = 2 To lastCol
            If col <> targetCol Then
                If Len(Cells(curRow, col).Value) > maxLen Then
                    maxLen = Len(Cells(curRow, col).Value)
                    longestTxt = Cells(curRow, col).Value
                End If
            End If
        Next col
        
        ' 将结果写入目标列
        Cells(curRow, targetCol).Value = longestTxt
    Next curRow
End Sub

使用步骤:

  1. 打开Excel文件,按Alt+F11打开VBA编辑器
  2. 插入模块,粘贴上述代码
  3. 返回Excel,选中黄色列的任意单元格
  4. 按Alt+F8选择GetLongestText并执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:33:38