Excel VBA使用通配符replacestring内的string

我有一个困难的情况,迄今没有find解决scheme的运气。

我的VBA收集的数字是$80,000.50. 我试图让VBA删除最后一个期间,使其看起来像$80,000.50但没有使用权利()。

问题是在最后一段时间后有隐藏的空间或字符,这将是一个很大的新问题处理,所以我只是在寻找像这样的东西:

replace("$80,000.50.",".**.",".**")

这在VBA中可能吗?

我不能留下评论所以….

那么InStrRev呢?

 Private Sub this() Dim this As String this = "$80,000.50." this = Left(this, InStrRev(this, ".") - 1) Debug.Print ; this End Sub 

怎么样:

 Sub dural() Dim r As Range For Each r In Selection s = r.Text l = Len(s) For i = l To 1 Step -1 If Mid(s, i, 1) = "." Then r.Value = Mid(s, 1, i - 1) & Mid(s, i + 1) Exit For End If Next i Next r End Sub 

这将删除最后一个时期,并保持所有其他字符不变。 之前:

在这里输入图像说明

之后:

在这里输入图像描述

编辑#1

该版本不需要循环遍历单元格中的字符:

 Sub qwerty() Dim r As Range For Each r In Selection If InStr(r.Value, ".") > 0 Then r.Characters(InStrRev(r.Text, "."), 1).Delete Next r End Sub 

中期+查找

您可以使用Mid和Findfunction。 像这样:

在这里输入图像说明

Find将find第一个点. 字符。 如果您收集的所有值都是带有2位小数的货币(以文本forms存储),则此function可以正常工作。

公式为: =MID(A2,1,FIND(".",A2)+2)

VBA解决scheme

 Function getStringToFirstOccurence(inputUser As String, FindWhat As String) As String getStringToFirstOccurence = Mid(inputUser, 1, WorksheetFunction.Find(FindWhat, inputUser) + 2) End Function 

其他可能的解决scheme,提示

修剪+清除+replace(Char(160)): Chandoo – 不可修饰的空间 – Excel公式
最终,您可以将正则expression式实现为Excel UDF: VBScript的正则expression式支持

最短的解决scheme

只需使用Val命令。 我以为这是一个数字呢? 摆脱逗号和美元符号,然后转换为价值,这将忽略第二点和任何其他尾随的字符! 鲁棒性未经testing,但似乎工作…

 Dim myString as String myString = "$80,000.50. junk characters " ' Remove commas and dollar signs, then convert to value. Dim myVal as Double myVal = Val(Replace(Replace(myString,"$",""),",","")) ' >> myVal = 80000.5 ' If you're really set on getting a formatted string back, use Format: myString = Format(myVal, "$000,000.00") ' >> myString = $80,000.50 

从文档中 ,

Val函数停止读取第一个字符处的string,它无法识别为数字的一部分。 通常被认为是数值的一部分的符号和字符(例如美元符号和逗号)不被识别。

这就是为什么我们必须首先删除美元符号,为什么它忽略了第二个点后面的所有垃圾,或者为什么最后什么都不是数字?

使用string

编辑:我先写这个解决scheme,但现在认为上述方法更全面和更短 – 在这里完整性。

Trim()删除string末尾的空格。 那么你可以简单地使用Left()来摆脱最后一点…

 ' String with trailing spaces and a final dot Dim myString as String myString = "$80,000.50. " ' Get rid of whitespace at end myString = Trim(myString) ' Might as well check if there is a final dot before removing it If Right(myString, 1) = "." Then myString = Left(myString, Len(myString) - 1) End If ' >> myString = "$80,000.50"