如何在Excel中删除单元格内的空行?

5
我是一位有用的助手,可以为您进行文本翻译。以下是您需要翻译的内容:

我在单个Excel单元格中有多行文本。我想要从该文本中删除所有空行。我必须明确表示,我不想删除所有换行符。

示例A:

There is a place where the sidewalk ends
And before the street begins,
And there the grass grows soft and white,

And there the sun burns crimson bright,
And there the moon-bird rests from his flight

To cool in the peppermint wind.

"

...应该翻译成:

"
There is a place where the sidewalk ends
And before the street begins,
And there the grass grows soft and white,
And there the sun burns crimson bright,
And there the moon-bird rests from his flight
To cool in the peppermint wind.

例子 B:





There is a place where the sidewalk ends
And before the street begins,
And there the grass grows soft and white,
And there the sun burns crimson bright,
And there the moon-bird rests from his flight

To cool in the peppermint wind.




"

...应该翻译为:

"
There is a place where the sidewalk ends
And before the street begins,
And there the grass grows soft and white,
And there the sun burns crimson bright,
And there the moon-bird rests from his flight
To cool in the peppermint wind.

我想要去除空行,因为:
  • 查看电子表格时,可能会看起来某些单元格为空,但实际上它们有几个空行后仍有文本;

  • 我需要清理数据,以便导入到另一个存储解决方案中。

Microsoft有一些关于如何在Excel中去除空格的文档。

但它并没有具体描述去除空行的解决方案:


空行总是为空的,还是偶尔包含空格? - Orbling
如果只有空白行,则使用=SUBSTITUTE(A1, CONCATENATE(CHAR(13),CHAR(10),CHAR(13),CHAR(10)),CONCATENATE(CHAR(13),CHAR(10)))进行处理,其中A1是您要处理的单元格。 - Orbling
以上方法唯一的问题是它无法捕获多个空行,虽然可以多次应用以捕获,但在直接公式中受到限制。否则正则表达式会很好用,但令人恼火的是它不内置于Excel中,因此需要一些VBA代码。 - Orbling
@Orbling 微软支持正则表达式库。 - David Zemens
@DavidZemens:是的,我知道 - 但是Excel没有内置的正则表达式函数。您必须通过VBA从相关库中公开它们。 - Orbling
如果文本字符串位于单元格A1中,则可以在任何要仅删除空白行的单元格中插入以下数组公式。=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,CHAR(10)&"",CHAR(10)&"^"),CHAR(10)&"^"&CHAR(10)&"^","%"),"%",CHAR(10)) [Ctrl、Shift和Enter键] - Miaka3
2个回答

3

VBA解决方案:

Sub DoubleReturn()
    Range("A1").Select
    Selection.Replace What:="" & Chr(10) & "" & Chr(10) & "", Replacement:="" & Chr(10) & ""
End Sub

非VBA解决方案:

在查找框中输入:ALT+0010(两次)以打出两个回车符。

在替换框中输入:ALT+0010(一次)


3

Excel确实支持一些正则表达式,但你需要一些疯狂的VBA才能使用它。我进行了一些测试,似乎可以工作。

只需将以下内容放入模块中,您就可以使用单元格公式,例如=ClearLineBreaks(A1)

Function ClearLineBreaks(txt As String)
    Application.Volatile
    With CreateObject("VBScript.RegExp")
        .Pattern = "(\r|\n) ?"
        .Global = True
        ClearLineBreaks = Trim(.Replace(txt, " "))
    End With
End Function

1
你会注意到我说它需要 VBA,而不是没有 VBA。我的意思是在常规函数中不可用。请注意,您要将其调整为仅清除双重换行符,而不是单个换行符。 - Orbling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接