宏将数字格式更改为一定的小数位数

时间:2016-11-23 13:15:30

标签: regex excel vba decimal-point

我希望使用宏来更改单元格中显示的小数位数。我希望宏可以使用各种自定义格式,我有以下示例,我想要正确更改:

$ #,##0.00" Test 0.00";[Red]$ -#,##0.00" Test 0.00"
$ #,##0.00" Test 0.00";[Red]$ -#,##0.00" Test 0.00"
$ #,##0.0000" Test 0.00";[Red]$ -#,##0.0000" Test 0.00"
$ #,##0" Test 0.00";[Red]$ -#,##0" Test 0.00"
$ #,##0.0000000" Test 0.00";[Red]$ -#,##0.0000000" Test 0.00"
$ #,##0%" Test 0.00";[Red]8" Test 0.00"
$ #,##0%" Test 0.00";[Red]8" Test 0.00"
"Test 0.0000"$ #,##0.0000000" Test 0.00";[Red]"Test 0.0000"$ -#,##0.0000000" Test 0.00"
"Test 0.0000"$ #,##0%" Test 0.00";[Red]"Test 0.0000"8" Test 0.00"
"Test 0.0000"$ #,##0%" Test 0.00";[Red]"Test 0.0000"8" Test 0.00"

注意,我在引号内使用了0.00。我不希望脚本改变它,我希望它们保持这种状态。

我已经开始使用RegEx,但我不确定这是否是正确的方法:

Sub ChangeDecimalPoints(sRange As Range, DP As Integer)
Dim sCell As Range, sFmt As String
Dim regEx As New VBScript_RegExp_55.RegExp, arrMatch As Variant, i As Long

For Each sCell In sRange
    sFmt = sCell.NumberFormat
    With regEx
        .Global = True
        .ignorecase = True
        .Pattern = "[^""]+|(0\.[0]+)"
        If .test(sFmt) Then
            Set arrMatch = .Execute(sFmt)
            i = 0
            Do Until i = arrMatch.Count
                Debug.Print sFmt, arrMatch(i)
                i = i + 1
            Loop
        End If
    End With
Next sCell
End Sub

编辑: 要显示我希望如何更改的示例,如果我运行以下内容(假设上面的列表显示.NumberFormat的{​​{1}}):
Selection

我希望上面的输出如下:

ChangeDecimalPoints Selection, 2

2 个答案:

答案 0 :(得分:0)

在整个下午都在考虑这个问题之后,我找到了一个适用于我上面发布的所有示例格式的答案:

Sub ChangeDecimalPoints(sRange As Range, DP As Integer)
Dim sCell As Range, sFmt As String, sNewFmt As String
Dim regEx As New VBScript_RegExp_55.RegExp, arrMatch As Variant, i As Long, arrReplace As Variant

sNewFmt = "0" & IIf(DP > 0, ".", "")
For i = 1 To DP
    sNewFmt = sNewFmt & "0"
Next i

For Each sCell In sRange
    sFmt = sCell.NumberFormat
    With regEx
        .Global = True
        .ignorecase = True
        .Pattern = "[\""].*?[\""]|(0\.?0*)"
        If .test(sFmt) Then
            Set arrMatch = .Execute(sFmt)
            For i = arrMatch.Count - 1 To 0 Step -1
                If Not IsEmpty(arrMatch(i).submatches(0)) Then
                    sFmt = WorksheetFunction.Replace(sFmt, arrMatch(i).FirstIndex + 1, arrMatch(i).Length, sNewFmt)
                End If
            Next i
        End If
    End With
    sCell.NumberFormat = sFmt
Next sCell
End Sub

我不确定是否有办法让它在没有.submatches的情况下工作,我假设可能有一种方法使用`regEx.Replace(输入,“$ match”)但是我太懒了这也适用。

答案 1 :(得分:0)

我会去

(?<=#,##)([^%"]+)

将匹配#,##和之后找到的第一个引用或%之间的任何内容,并将其放入一个组中。

然后用0.00替换你得到的东西。

相关问题