替换方法并更改格式?

时间:2019-02-18 10:27:30

标签: excel vba

我正在使用vba方法“替换”,并且需要将每个“ / ”更改为“,”。这看起来很简单,所以我使用:

ActiveWorkbook.Worksheets(2).Cells.Replace What:="_/_", Replacement:=",", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=True, _
    ReplaceFormat:=True

问题在于,其中一个单元格的值如下:

04 _ / _ 2018

结果是:

4,2018

代替:

04,2018

在我的工作簿中,所有单元格在应用代码之前和之后均具有文本格式。我的猜测是,Excel在处理过程中暂时将格式更改为常规格式,并且对于数字为零的情况,它没有必要进行截止。

我试图通过更改方法的参数(无此方法)并将小数点分隔符从“,”更改为“。”来绕过此问题。这在使用Excel手动查找和替换时很有帮助,但是当我记录下来并尝试用作Macro时,它不起作用。在这种情况下,我该怎么做以防止Excel截断零?

2 个答案:

答案 0 :(得分:0)

默认情况下,Excel中会自动删除前导零。因此04,2014更改为4,2014。解决此问题的一种方法是将单元格设置为文本格式,在Replace()之前添加以下行:

ActiveWorkbook.Worksheets(2).Cells.NumberFormat = "@"

格式化为文本有很多不愉快的变化,例如文本会显示在左侧,默认情况下Excel无法识别日期/数字。

这是代码的简单示例,更改了1个单元格:

Sub TestMe()
    ActiveWorkbook.Worksheets(1).Cells.NumberFormat = "General"
    Range("B5") = "05_2018"
    ActiveWorkbook.Worksheets(1).Cells.NumberFormat = "@"
    Range("B5") = Replace(Range("B5"), "_", ".")
End Sub

对于较大的未知范围,格式化为文本可以这样工作:

Sub TestMe()

    Worksheets(1).Cells.NumberFormat = "General"
    Range("A1:B15") = "05_2018"

    Dim findRange As Range
    Set findRange = Worksheets(1).Cells.Find("_")
    Dim myCell As Range

    If Not findRange Is Nothing Then
        For Each myCell In findRange
            myCell.Replace "_", ","
        Next myCell
    End If

End Sub

答案 1 :(得分:0)

如果要04,2018,请使用.Find/.FindNext,然后替换并重新构建值,然后再放置到单元格中。

这是您要尝试的吗?

Sub Sample()
    Dim oRange As Range, aCell As Range, bCell As Range
    Dim ws As Worksheet
    Dim ExitLoop As Boolean
    Dim SearchString As String

    On Error GoTo Whoa

    Set ws = Worksheets("Sheet1")
    Set oRange = ws.UsedRange

    SearchString = "_/_"

    Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        Set bCell = aCell

        If Left(aCell.Value, 1) = 0 Then
            aCell.Value = "'" & Replace(aCell.Value, SearchString, ",")
        Else
            aCell.Value = Replace(aCell.Value, SearchString, ",")
        End If

        Do While ExitLoop = False
            Set aCell = oRange.FindNext(After:=aCell)

            If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                If Left(aCell.Value, 1) = 0 Then
                    aCell.Value = "'" & Replace(aCell.Value, SearchString, ",")
                Else
                    aCell.Value = Replace(aCell.Value, SearchString, ",")
                End If
            Else
                ExitLoop = True
            End If
        Loop
    Else
        MsgBox SearchString & " not Found"
    End If

    Exit Sub
Whoa:
    MsgBox Err.Description
End Sub

屏幕截图

enter image description here