使用VBA删除开头和结尾的空格,但将空格保留在字符串中 [英] Use VBA to remove leading and trailing blank spaces but keeping blanks within a string

查看:136
本文介绍了使用VBA删除开头和结尾的空格,但将空格保留在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理和格式化从会计系统获得的一组数据,并且已经能够创建VBA代码以在特定列范围内使用TRIM或CLEAN函数.

I'm trying to clean and format some set of data obtained from an accounting system and I have been able to create VBA code to use TRIM or CLEAN functions in the specific column ranges.

问题是我需要在字符串中保留空格(可以是2、3或更多空格),但仍要删除前导/尾随空格,并且上述函数将内部空格减小为1.这是行不通的对我而言,因为数据被用作与流程其他步骤中的其他信息进行匹配的关键.请记住,前导/尾随空格可能是空格键,任何其他显示为空格甚至包含换行符的字符的结果,所以再次,我希望将所有这些空格除去但内部空格.字符串可以由字母数字字符组成.

The thing is that I need to keep the blank spaces within the strings (can be 2, 3 or more blanks) but still remove the leading/trailing spaces and the mentioned functions reduce the inner spaces to 1. This does not work for me as the data is used as a key to match other information in further steps of the process. Bare in mind that leading/trailing blanks can be the result of space bar key, any other character that appears as a blank or even contains line breaks, so again, I want all of these removed but inner blanks. Strings can be made of alphanumeric characters.

我在Private Sub中使用此代码(通过单击工作表中的按钮来执行代码).

I'm using this in a Private Sub (code is execute via a click in a button placed in the worksheet).

Dim rng1a As Range
Dim Area1a As Range
Set rng1a = Range("F2:F35001")

  For Each Area1a In rng1a.Areas
    Area1a.NumberFormat = "@"
    Area1a.Value = Evaluate("IF(ROW(" & Area1a.Address & "),CLEAN(TRIM(" & Area1a.Address & ")))")
  Next Area1a

示例(在F2:F35001范围内):

Example (in range F2:F35001):

Original:  Sample  Text   for Review.     *(there are blanks after the string)
Result:Sample Text for Review.
Desired:Sample  Text   for Review.

我进行了几周的研究,但一直没有找到一种解决方案,可以使内部空白保持原样",并避免在论坛中重复出现尽可能多的问题.预先感谢您的帮助.

I made some research for a couple of weeks and haven't been able to find a solution that keeps the inner blanks "as is" and avoid as much as possible duplicate question in the forum. Thanks in advance for the help.

推荐答案

您可以使用正则表达式:

You can do this with regular expressions:

Option Explicit
Function trimWhiteSpace(s As String) As String
    Dim RE As Object

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True
    .Pattern = "^\s*(\S.*\S)\s*"
    trimWhiteSpace = .Replace(s, "$1")
End With
End Function

正则表达式的解释

^\s*(\S.*\S)\s*

选项:区分大小写;^ $匹配行间的中断

Options: Case sensitive; ^$ match at line breaks

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆