简体   繁体   中英

How to remove the last character of a word in a text string and insert to another cell using VBA in Excel?

Everything is working except for that little comma in the 5th word. How to remove that? My code is as follows.

The text looks like this: The data as of 20.12.2019, and so on. I only want 20.12.2019 without that comma. Any clue? Thanks.

Public Function FindWord(Source As String, Position As Integer)

Dim arr() As String
arr = VBA.Split(Source, " ")
xCount = UBound(arr)
If xCount < 1 Or (Position - 1) > xCount Or Position < 0 Then
    FindWord = ""
Else
    FindWord = arr(Position - 1)
End If
End Function

subroutine calls the function.

Sub InsertDate()

Sheets("Sheet1").Range("B3").Value = FindWord(Sheets("Sheet2").Range("A2"), 5)

End Sub

So just for fun, a short introduction to regular expressions (which, by no means, I am an expert in):

Sub Test()

Dim str As String: str = "The data as of 20.12.2019, and so on."
Dim regex As Object: Set regex = CreateObject("VBScript.RegExp")

regex.Pattern = "\b(\d{2}.\d{2}.\d{4})"
regex.Global = True

Debug.Print regex.Execute(str)(0)

End Sub

This would be good practice if your string won't follow that same pattern all the time. However when it does, there are some other good alternatives mentioned in comments and answers.

One option is to Replace :

Sub InsertDate()
    With Sheets("Sheet1").Range("B3")
        .Value = FindWord(Sheets("Sheet2").Range("A2"), 5)
        .Value = Replace(.Value, ",", "")
    End With
End Sub

This is still text-that-looks-like-a-date , so you can call DateValue to convert it.

.Value = Replace(.Value, ",", "")
.Value = DateValue(.Value) '<~ add this line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM