如何从单元格中删除换行符,但将地址格式保留在同一单元格VBA中

问题描述 投票:0回答:2

我试图删除换行符的单元格是这样的:

(Blank line break)
Test Company
1640 Test Avenue,
New York, NY 10035
(000)123-456    
(Blank line break)

我想删除有换行符的两行。香港专业教育学院尝试使用查找和替换来替换替换与替代代码0010的换行符,但它创建一个长字符串。

我想最终得到这个:

Test Company
1640 Test Avenue,
New York, NY 10035
(000)123-456  

任何帮助,将不胜感激。

excel vba formatting
2个回答
1
投票

像这样的东西

Dim v
v = Trim(cell.Value)
if left(v,1)=vblf then v = right(v, len(v)-1)  'remove leading break
if right(v,1)=vblf then v = left(v, len(v)-1)  'remove trailingbreak
v = replace(v, vbLf & vbLf, vbLf)              'remove blank lines
cell.value=v

0
投票

这是一个类似于工作表TRIM函数的UDF,但允许您指定要修剪的字符:

Option Explicit
Function trimCHAR(ByVal S As String, char As String)
  Dim RE As Object
  Dim I As Long

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True

'need to do separately, otherwise multiple chars within will
'be removed
        .Pattern = char & "$"
        S = .Replace(S, "") 'Remove extra chars within or at end of string
        .Pattern = "^" & char
        S = .Replace(S, "") 'Remove extra chars at start of string
End With
trimCHAR = S
End Function

在您的情况下,您可以使用它:

=trimCHAR(cell_ref,CHAR(10))

或者您可以将它用作宏的一部分,迭代所有要处理的单元格。

这个想法来自Power Query的Text.Trim函数,该函数仅适用于字符串的开头和结尾,但允许指定任何字符串;以及Ken Puls对它的改编,它增加了工作表函数TRIM功能,用一个单独的字符串替换字符串中的顺序“字符”。

© www.soinside.com 2019 - 2024. All rights reserved.