Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Replace Part of Time String

Tags:

replace

time

vba

Column C has Time (formatted as text as sheet will be exported as csv) in format HH:mm:ss.

C1, C2, C3 values are of Time 09:15:00, 09:16:00, 09:17:00 respectively till 15:29:00

Need to REPLACE ONLY the last ":00" part with ":59"

---CATCH--- In column C there will be values such as 10:00:00 or 11:00:00 or 12:00:00

This means a direct replace ":00" with ":59" would corrupt the values of exact 10'o clock , 11'o clock etc..

Column C will be filled with thousands of such data points. My logic below will not work i guess:

{

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")

}

i know the above code is wrong but that's all i could come up with.

request for help complete this logic..

EDIT: Was not quite elaborate in explaining. Even these full hour values need to be replaces such as: 10:00:59, 11:00:59, 12:00:59

like image 677
Vaibhav Avatar asked Oct 05 '15 13:10

Vaibhav


People also ask

How do I replace part of a string in VBA?

Use the VBA Replace function to replace a substring of characters in a string with a new string. VBA Replace is similar to the Excel SUBSTITUTE function; both can be used to replace a portion of a string with another.

Is there a Replace function in VBA?

The VBA REPLACE function is listed under the text category of VBA functions. When you use it in a VBA code, it replaces a substring from string with a new sub-string. In simple words, you can use REPLACE to replace a part of text with another text and it returns that new text in the result.

Is VBA replace case sensitive?

* This function is case sensitive (by default).


1 Answers

If the value does not end with 00:00 then update it to :59

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

Edit, to replace just the last 00:

Dim cell As Range

For Each cell In Range("C1", Range("C1").End(xlDown))
    cell.Value = Left$(cell.Value, 6) & "59"
Next
like image 64
Alex K. Avatar answered Sep 24 '22 11:09

Alex K.