Excel-VBA:无法插入换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10775235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:13:04  来源:igfitidea点击:

Excel-VBA: Unable to Insert Line Breaks

excelvbanewline

提问by Wassim AZIRAR

I need to insert lines in a cell, but I am unable to insert line breaks.

我需要在单元格中插入行,但我无法插入换行符。

For example :

例如 :

line1

line2

line3

第一行

线2

线3

With VBA code :

使用 VBA 代码:

             Ws.Cells(i, 2) = line1 & line2 & line3

I get :

我得到:

line1 line2 line3

线 1 线 2 线 3

How can I resolve this issue?

我该如何解决这个问题?

回答by Siddharth Rout

Is this what you are trying?

这是你正在尝试的吗?

Ws.Cells(i, 2).Value = "line1" & vbnewline & "line2" & vbnewline & "line3"

or

或者

Ws.Cells(i, 2).Value = "line1" & vbCrLf & "line2" & vbCrLf & "line3"

EDIT: Inserted quotes as mentioned in my comments.

编辑:插入了我的评论中提到的引号。

回答by jhfelectric

I have tested a few combinations and here are the results:

我测试了几种组合,结果如下:

cell(a,b) = line1 & vbCrLf & line2

result:
line1**
line2

结果:第1行
**第
2行

cell(a,b) = line1 & vbCr & line2

result:
line1line2

结果:
line1line2

cells(a,b) = line1 & vbLf & line2

result:
line1
line2

结果:
line1
line2

In the above results the * denotes a blank space (I don't know why), so the vbCrLf is not recommended when you want to center the cell content horizontally. My preference goes for vbLf.

在上面的结果中,* 表示一个空格(我不知道为什么),所以当你想水平居中单元格内容时,不推荐使用 vbCrLf。我更喜欢 vbLf。

回答by Ricardo Souza

Linebreaks in VBA are vbCrLfand you can concatenate them with the strings.

VBA 中的换行符是vbCrLf,您可以将它们与字符串连接起来。

回答by Holf

Ws.Cells(i, 2) = line1 & line2 & Chr(10) & line3

As per this answer.

根据这个答案。

回答by joshoff

FYI, you can prevent coding typos by using an easier-to-type variable name.

仅供参考,您可以通过使用更易于键入的变量名称来防止编码拼写错误。

bx = vbCrLf

textstring = "Hello everybody!" & bx & "This is my second line!"