3

我有一列我拾取递增的编号值,它们的格式是 xx_yy 所以第一个是 1_0,第二个是 1_1 依此类推,不,我们在 23_31

我想得到字符串的右侧,并且我已经正确地得到了左侧。使用

newActionId = Left(lastActionID, (Application.WorksheetFunction.Find("_", lastActionID, 1) - 1))

我希望做以下事情,下面是人类写作

nextSubid = entire stringvalue AFTER special character "_"

我试着从左到右切换,没有那么好,你有什么建议吗?

4

4 回答 4

4

您可以使用拆分功能来获取相关文本。

语法:拆分(表达式,[分隔符,[限制,[比较]]])

Option Explicit

Sub Sample()
    Dim id As String
    Dim beforeSplChr As String
    Dim afterSplChr As String

    id = "23_31"

    beforeSplChr = Split(id, "_")(0)
    afterSplChr = Split(id, "_")(1)

    Debug.Print beforeSplChr
    Debug.Print afterSplChr
End Sub

另一种方式

Debug.Print Left(id, (InStrRev(id, "_", -1) - 1)) '<~~ Left Part
Debug.Print Right(id, (InStrRev(id, "_", -1) - 1)) '<~~ Right Part
于 2020-03-02T08:42:53.923 回答
2

尽管 Siddharth Rout 在这里给出了可能被认为是更好的答案,但我觉得这值得补充:

要使用原始方法获取字符串的第二部分,您可能希望使用Mid函数代替Left,而不是尝试使用Right.

mid(string, start, [ length ] )从string
中返回length个字符,从起始位置开始 如果省略length,则返回从起始位置到字符串结尾的字符

newActionId = Mid(lastActionID, Application.WorksheetFunction.Find("_", lastActionID, 1) + 1)
于 2020-03-02T09:05:43.390 回答
1

只是为了好玩(Split是去这里的方式),使用正则表达式的另一种方式:

Sub Test()

Dim str As String: str = "23_31"

With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\d+"
    Debug.Print .Execute(str)(0) 'Left Part
    Debug.Print .Execute(str)(1) 'Right Part
End With

End Sub

顺便说一句,根据我的评论,您的第一个价值也可以通过以下方式实现:

Debug.Print Val(str)
于 2020-03-02T10:18:43.600 回答
0

字符串的拆分功能对于这种类型的查询非常有用。喜欢:

String s = "23_34";
String left = s.split("_")[0];
String right = s.split("_")[1];

Or you can also use combination of indexOf and substring method together.
String left = s.substring(0,s.indexOf('_')+1)
String right = s.substring(s.indexOf('_'));
于 2020-03-02T10:00:50.427 回答