从 VBA 中的字符串中提取子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11140931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:34:06  来源:igfitidea点击:

Extract substring from a string in VBA

vbaexcel-vbaexcel-2007substringexcel

提问by tonyf

I am looking to write some VBA code to obtain the following pieces of information from the following string with brackets and hyphens, i.e.

我正在寻找编写一些 VBA 代码以从以下带有括号和连字符的字符串中获取以下信息,即

ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term

ACOST 2012 定价表 - (PRJ 216664 - 金融服务器停用) - 12 个月期限

Using VBA for Excel 2007, I need to obtain the following two bits within this string and assigned to two different variables, i.e.:

使用 Excel 2007 的 VBA,我需要在此字符串中获取以下两位并分配给两个不同的变量,即:

  • 216664
  • Financial Server Decommission
  • 216664
  • 金融服务器退役

I tried the Mid()syntax but couldn't extract these two bits of info.

我尝试了Mid()语法,但无法提取这两位信息。

回答by Siddharth Rout

If the format is going to remain same then you can use this

如果格式要保持不变,那么您可以使用它

Sub Sample()
    Dim strSample As String

    strSample = "ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term"
    strSample = Split(Split(strSample, "(")(1), ")")(0)

    Debug.Print Trim(Split(Split(strSample, "-")(0), " ")(1))
    Debug.Print Trim(Split(strSample, "-")(1))
End Sub

回答by Alex K.

Another way;

其它的办法;

Data = "ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term"

dim re As object, matches as object: Set re = createobject("vbscript.regexp")
re.pattern="- \(.*?(\d+)\s+-\s+(.*?)\)(\s|$)"

with re.Execute(Data)
    msgBox  .item(0).SubMatches(0) & " / " & .item(0).SubMatches(1)
End with

Get the last group of digits after "- (" before a "-" surrounded by whitespace then get everything upto the next ) thats followed by whitespace or the end of the line"

获取“-”之后的最后一组数字(在由空格包围的“-”之前,然后将所有内容移到下一个),然后是空格或行尾”