Loading

【适用于WPS】删除单元格内的空行的宏

首先插入模块,复制以下宏粘贴进去,切换回表格中,选中你需要删除单元格内空行的单元格,最后切回宏,模块内按下F5运行即可

Sub RemoveEmptyLinesInSelectedCells()
    ' 声明变量
    Dim cell As Range
    Dim originalText As String
    Dim cleanedText As String
    Dim lines() As String
    Dim line As Variant
    Dim tempLines As New Collection ' 使用 Collection 来动态存储非空行
    Dim tempArray() As String ' 新增:用于将 Collection 转换为数组的临时数组
    Dim i As Long ' 新增:用于数组索引

    ' 检查是否有单元格被选中
    If Selection.Cells.Count = 0 Then
        MsgBox "请选择一个或多个包含需要处理的单元格。", vbExclamation
        Exit Sub
    End If

    ' 遍历选中区域中的每个单元格
    For Each cell In Selection
        originalText = cell.Value

        ' 如果单元格为空,则跳过
        If Trim(originalText) = "" Then
            GoTo NextCell
        End If

        ' 将文本按换行符(Chr(10))分割成行
        lines = Split(originalText, Chr(10))

        ' 清空临时存储非空行的 Collection
        Set tempLines = New Collection

        ' 遍历每一行
        For Each line In lines
            ' 如果当前行去除首尾空格后不为空,则添加到 Collection
            If Trim(line) <> "" Then
                tempLines.Add line
            End If
        Next line

        ' 将 Collection 中的所有行重新连接成一个字符串,每行之间用换行符分隔
        If tempLines.Count > 0 Then
            ' 将 Collection 转换为数组
            ReDim tempArray(1 To tempLines.Count) ' 重新定义数组大小
            For i = 1 To tempLines.Count
                tempArray(i) = tempLines.Item(i) ' 将 Collection 中的元素复制到数组
            Next i
            cleanedText = Join(tempArray, Chr(10)) ' 使用 Join 函数连接数组
        Else
            cleanedText = "" ' 如果没有非空行,则结果为空
        End If

        ' 更新单元格的值
        cell.Value = cleanedText

NextCell:
    Next cell

    MsgBox "已删除选中单元格内的多余空行。", vbInformation
End Sub

 

posted @ 2025-12-06 13:24  离者悲名  阅读(10)  评论(0)    收藏  举报