简体   繁体   English

如何在Excel中使用VBA删除文本字符串中单词的最后一个字符并插入到另一个单元格?

[英]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.除了第 5 个单词中的那个小逗号外,一切正常。 How to remove that?如何删除它? My code is as follows.我的代码如下。

The text looks like this: The data as of 20.12.2019, and so on.文本如下所示: The data as of 20.12.2019, and so on. I only want 20.12.2019 without that comma.我只想要20.12.2019没有那个逗号。 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 :一种选择是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.这仍然是text-that-looks-like-a-date ,因此您可以调用DateValue来转换它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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