Search code examples
vbaexcel

Inserting into an Excel VBA string


In JAVA or C++, we can do something along the line of myString.insert(position, word). Is there a way we can do the same in Excel VBA's string? In my worksheet, I have a string looks like this: 01 / 01 / 995, I wants to insert a 1 into the year, so make it 01 / 01 / 1995.

Dim test_date As String
test_date = "01 / 25 / 995"
test_date = Mid(test_date, 1, 10) & "1" & Mid(test_date, 11, 4)

Is there another easier / more elegant way to do it?


Solution

  • I dont think there is a cleaner way of doing it so you could just wrap it up in a function. Another way of doing it would be with replace, but it's not any cleaner.

    Function Insert(source As String, str As String, i As Integer) As String
        Insert = Replace(source, tmp, str & Right(source, Len(source)-i))
    End Function 
    

    or just modify what you have

    Function Insert(source As String, str As String, i As Integer) As String
        Insert = Mid(source, 1, i) & str & Mid(source, i+1, Len(source)-i)
    End Function