我有一张表,我需要删除空格,所以我可以比较它我使用的是我在这里找到的一个函数和一个将所有值放入数组的子程序(速度)但我无法得到它任何想法为什么工作。我得到了
ByRef参数类型不匹配错误
Public Function RemoveWhiteSpace(target As String) As String
With New RegExp
.Pattern = "\s"
.MultiLine = True
.Global = True
RemoveWhiteSpace = .Replace(target, vbNullString)
End With
End Function
Sub stringRangeToClean()
Dim r As Variant
Dim i As Long
r = ActiveWorkbook.Sheets("Trent BASE DATA").UsedRange
For i = 2 To UBound(r)
r(i, 10).Value2 = RemoveWhiteSpace(r(i, 10))
Next i
End Sub
现在尝试这个我已经意识到我实际上是我(我,9) 但我在RegExp行上收到用户定义类型错误的错误
Public Function RemoveWhiteSpace(target As String) As String
With New RegExp
.Pattern = "\s"
.MultiLine = True
.Global = True
RemoveWhiteSpace = .Replace(target, vbNullString)
End With
End Function
Sub stringRangeToClean()
Dim r As Variant
Dim i As Long
Dim txt As String
r = ActiveWorkbook.Sheets("Trent BASE DATA").UsedRange
For i = 2 To UBound(r)
txt = r(i, 9)
txt = RemoveWhiteSpace(txt)
Next i
End Sub
答案 0 :(得分:6)
在这里,只需删除空格就不需要正则表达式。您的主要挑战是定义您的基本VBA范围:
Sub tgr()
With ActiveWorkbook.Sheets("Trent BASE DATA")
.Range("J2", .Cells(.Rows.Count, "J").End(xlUp)).Replace " ", vbNullString
End With
End Sub
答案 1 :(得分:2)
试试这样:
Public Function RemoveWhiteSpace(target As String) As String
Dim RegExp As Object
Set RegExp = CreateObject("VBScript.RegExp")
With RegExp
.Pattern = "\s"
.MultiLine = True
.Global = True
RemoveWhiteSpace = .Replace(target, vbNullString)
End With
End Function
这样,您对regExp
变量使用后期绑定,因此您和您的用户都不必添加任何其他库。
如果要使用早期绑定,则应将Microsoft VBScript Regular Expressions 5.5"
库添加到VBA使用的库中。早期绑定会给你一些时间奖励,它提供IntelliSense
。
此处所选答案逐步说明了如何添加库:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
关于你的代码 - 这是非常简单的循环,尝试这样做:
Sub StringRangeToClean()
Dim r As Variant
Dim myCell As Range
r = ActiveWorkbook.Sheets("Trent BASE DATA").UsedRange
For Each myCell In r
myCell = RemoveWhiteSpace(txt)
Next myCell
End Sub
这样每个细胞都会被检查,白色空间会被移除。