如何用其他值替换单元格中的前几个空格

How to replace first few spaces in cell with other values

我有日期值,例如显示为“01 01 1970 12:00”。由于日期使用 spaces 而不是“-”或“/”,因此 excel 无法将其识别为日期值。

正在使用 Range = Replace(Range, " ", "/", 1, 2) 要么 Range = Replace(Range, " ", "/") return类型不匹配错误

正在使用 Range.Replace what:=" ", replacement:="/", lookat:=xlPart 有效,但它也替换了最后一个 space 并将值变为我不想要的“01/01/1970/12:00”。它应该 return 作为日期格式。

函数 Replace 的第一个值是 String

所以您必须将 Range 更改为 Cell 的值:

例如:值必须替换为 Cell(1,1)

Range = Replace(Range, " ", "/", 1, 2)

收件人:

ActiveSheet.Cells(1, 1).Value = Replace(ActiveSheet.Cells(1, 1).Value, " ", "/", 1, 2)

替换日期分隔符

Excel公式(SUBSTITUTE)

Sub ReplaceDateSeparator()

    Const FirstRowAddress As String = "C2:D2"
    Const SearchSeparator As String = " "
    Const ReplaceSeparator As String = "/"
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim rg As Range
    
    With ws.Range(FirstRowAddress)
        Dim lCell As Range: Set lCell = .Resize(ws.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , xlByRows, xlPrevious)
        If lCell Is Nothing Then Exit Sub
        Set rg = .Resize(lCell.Row - .Row + 1)
    End With

    rg.Value = ws.Evaluate("=SUBSTITUTE(SUBSTITUTE(" & rg.Address _
        & ",""" & SearchSeparator & """,""" & ReplaceSeparator _
        & """,1),""" & SearchSeparator & """,""" & ReplaceSeparator & """,1)")

End Sub

VBA (Split/Join)

Sub ReplaceDateSeparatorVbaTEST()

    Const FirstRowAddress As String = "C2:D2"
    Const SearchSeparator As String = " "
    Const ReplaceSeparator As String = "/"
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim rg As Range
    
    With ws.Range(FirstRowAddress)
        Dim lCell As Range: Set lCell = .Resize(ws.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , xlByRows, xlPrevious)
        If lCell Is Nothing Then Exit Sub
        Set rg = .Resize(lCell.Row - .Row + 1)
    End With

    ReplaceDateSeparatorVba rg, SearchSeparator, ReplaceSeparator

End Sub

Sub ReplaceDateSeparatorVba( _
        ByVal rg As Range, _
        Optional ByVal SearchSeparator As String = " ", _
        Optional ByVal ReplaceSeparator As String = "/")
    
    Dim rCount As Long: rCount = rg.Rows.Count
    Dim cCount As Long: cCount = rg.Columns.Count
    
    Dim Data As Variant
    
    If rCount + cCount = 2 Then ' one cell
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
    Else ' multiple cells
        Data = rg.Value
    End If
    
    Dim Arr() As String
    Dim cValue As Variant
    Dim r As Long
    Dim c As Long
    
    For r = 1 To rCount
        For c = 1 To cCount
            cValue = Data(r, c)
            If Not IsError(cValue) Then ' exclude error values
                Arr = Split(Data(r, c), SearchSeparator, 3)
                Data(r, c) = Join(Arr, ReplaceSeparator)
            End If
        Next c
    Next r
    
    rg.Value = Data
    
End Sub