VBA:替换部分时间字符串

时间:2015-10-05 13:03:18

标签: vba time replace

C列有时间(格式为文本,工作表将导出为csv),格式为HH:mm:ss。

C1,C2,C3值分别为时间09:15:00,09:16:00,09:17:00至15:29:00

需要仅使用“:59”

替换最后一个“:00”部分

--- --- CATCH 在C列中,将存在诸如10:00:00或11:00:00或12:00:00

之类的值

这意味着用“:59”直接替换“:00”会破坏精确10'时钟,11'时钟等的值。

C列将填充数千个此类数据点。以下我的逻辑无效:

{

Dim secrep As String
LastRow = Cells(Rows.Count, "C").End(xlUp).Row
Secsz = Range("C1:C" & LastRow).Select
seczero = Right(Secsz, 2)
secrep = Replace(Secsz, ":00", ":59")

}

我知道上面的代码是错的,但这就是我能想到的。

请求帮助完成此逻辑..

编辑: 解释时不太精细。 即使这些全小时值也需要替换,例如:10:00:59,11:00:59,12:00:59

4 个答案:

答案 0 :(得分:2)

如果该值未以$.ajax({ url: GetBaseURL() + '/api/MyController/PutMethod', type: 'put', data: dataObject, contentType: 'application/json', timeout: AJAX_TIMEOUT, success: function () { self.CallOtherFunction(); }); 结尾,则将其更新为00:00

:59

编辑,仅替换 last Dim cell As Range For Each cell In Range("C1", Range("C1").End(xlDown)) If Right$(cell.Value, 5) <> "00:00" Then cell.Value = Left$(cell.Value, 6) & "59" End If Next

00

答案 1 :(得分:2)

你走在正确的轨道上。你只需要首先拆分字符串,在后半部分替换,然后再连接。这是一个通用功能,您可能希望通过一些错误处理来增强功能:

Function ReplaceEnd(s As String, endCount As Integer, replaceWhat As String, replaceWith As String)
    Dim baseString As String
    Dim replaceString As String

    baseString = Left(s, Len(s) - endCount)
    replaceString = Right(s, endCount)

    ReplaceEnd = baseString & Replace(replaceString, replaceWhat, replaceWith)
End Function

编辑:示例用法:

secrep = ReplaceEnd(Secsz, 3, ":00", ":59")

答案 2 :(得分:1)

你可以用这个:

Public Function AlterTime(rInputRange As Range)

    Dim oCell   As Range

    For Each oCell In rInputRange.Cells
        oCell = TimeSerial(Hour(oCell), Minute(oCell), 59)
    Next oCell

End Function

答案 3 :(得分:0)

使用拆分功能,然后进行分析和修改。

Private Sub CommandButton1_Click()
    Dim ws            As Excel.Worksheet
    Dim lastRow       As Long
    Dim szTimeParts() As String
    Dim lRow          As Long

    lRow = 1
    lastRow = ws.Cells(ws.Rows.count, "C").End(xlUp).Row

    Set ws = ActiveWorkbook.Sheets("Sheet1")
    ws.Activate

    'Loop through the rows
    Do While lRow <= lastRow

        'Make sure we have a value to read into our string
        If ws.Range("C" & lRow).Value <> "" Then
            szTimeParts = Split(Trim(ws.Range("C" & lRow).Value), ":")
            If szTimeParts(1) <> "00" Then
                ws.Range("C" & lRow).Value = szTimeParts(0) & ":" & szTimeParts(1) & ":59"
            End If
        End If
        lRow = lRow + 1
    Loop

End Sub