如何在VBA中的Concat功能中放置换行符

时间:2018-11-23 11:11:18

标签: vba newline concat

我有一个非常具体的问题,我正在尝试使用换行符将值连接为字符串,我尝试了所有可能,但没有任何效果。我尝试了vbnewline,vbLf,CHR(10)。

Range("M2:M" & AfterDuplastRow).Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
Range("M1").Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Formula = _
"=IF(F2=""" & meal & """," & _
"IF(F1<>F2,B2,Concat(M1,CHR(10),B2)),"""")"

我也这样尝试过

ActiveCell.Formula = _
"=IF(F2=""" & meal & """," & _
"IF(F1<>F2,B2,Concat(M1," & CHR(10) & ",B2)),"""")"

谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

使用常量vbNewLine

ActiveCell.Formula = "=IF(F2=""" & meal & """,IF(F1<>F2,B2,Concat(M1," & vbNewLine & ",B2)),"""")"

答案 1 :(得分:0)

听起来好像是XY Problem ...

即使您包括换行(vbNewLine,回车(vbCr),换行(vbLf)或回车换行(vbCrLf),如果为该单元格启用了自动换行,则在该单元格中可见。

这样,请尝试以下简单更改:

Range("M2:M" & AfterDuplastRow).Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
Range("M1").Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Formula = "=IF(F2=""" & meal & """," & _
    "IF(F1<>F2,B2,Concat(M1,CHR(10),B2)),"""")"
Range("M1").WrapText = True 'This line should fix your issue

(此外,您可能想阅读How to avoid using Select in Excel VBA