vba - 如何从 Excel 中的单元格中删除空行(VBA)

标签 vba excel

这是我试图通过工作表中包含字符串的所有单元格实现的目标,但到目前为止取得的成功有限:

|示例 |
cell1_empty_line
cell1_text1
cell1_empty_line
+--------------------------------+
cell2_text1
cell2_emptyline
cell2_text2
+--------------------------------+
cell3_emptyline
cell3_emptyline
cell3_text1
+--------------------+

|预期结果 |
cell1_text1
+--------------------------------+
cell2_text1
cell2_text2
+--------------------------------+
cell3_text1
+--------------------+

对于这样的宏有什么建议吗?

非常感谢。

最佳答案

使用此宏删除所有单元格内的任何空行:

Sub TrimEmptyLines()
    Dim cel As Range, s As String, len1 As Long, len2 As Long
    For Each cel In ActiveSheet.UsedRange
        If Not IsError(cel.Value2) Then
            If InStr(1, cel.text, vbLf) > 0 Then
                s = Trim(cel.Value2)
                Do ' remove duplicate vbLf
                    len1 = Len(s)
                    s = Replace$(s, vbLf & vbLf, vbLf)
                    len2 = Len(s)
                Loop Until len2 = len1

                ' remove vblf at beginning or at end
                If Left$(s, 1) = vbLf Then s = Right$(s, Len(s) - 1)
                If Right$(s, 1) = vbLf Then s = Left$(s, Len(s) - 1)

                cel.value = Trim$(s)
            End If
        End If
    Next
End Sub

关于vba - 如何从 Excel 中的单元格中删除空行(VBA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42841374/

相关文章:

c# - 使用 C# 对 Excel 工作表运行 VBA 宏

VBA 集 = 不同工作簿上的工作表

vba - 将表格列中的所有单元格设置为特定值

sql - 为什么 Clng 在这些场景中的工作方式不同,并且可以在 SQL Server 中重现吗? (不是银行家四舍五入)

excel - VBa 和 Excel : sum up highlighted cells value from specific item number and then subtract to cells value from other table and display in next column

excel - 使用perl将多种格式应用于excel中的相同数据

vba - 循环遍历当前事件工作表中 Excel VBA 中的所有命名范围

vba - 是否有将 Excel 文件格式/设置保存到对象的标准过程?

python - 如何将使用 Xlsxwriter 创建的公式中的值读入 Pandas 数据帧?

Java-Spring-JSP 下载 xls 文件 - POST 正常,GET 不起作用