如何使用VBScript或VBA实现以下场景?

时间:2018-05-28 12:06:09

标签: vba excel-vba vbscript excel

我在变量中有文字如下:

 4.1.6.1    Display of user roles and system versions

[4.01.070]
It must be possible for a user logged into a named XXXXXX project, 
to have all user information and all granted user roles displayed in a simple way. 
An example of the displayed information is displayed below:

User Name: XXXX
Full Name: XXXXX XXXX
e-Mail: XXXX@XXXXXX.com
Status: Active
Deactivation Date: 23 Marts 2028
Granted User Roles:     
    Test Case Author
    Requirement Author
Release manager
Description:
  Please note this user was trained in XXXXX in spring 1903.

[4.01.072]
When pressing the About button, the following information should be shown:
iAuthorize DLL version: [Major].[Minor].[Bug].[0] 
Workflow Script version:    [Major].[Minor].[Bug]
Std. Template version:  [XXXXX VX or XXXXXX VX]

The HP XXXX XXXXX version should be the name of the item called "XXXXX Version" on the XXXXX project list.

在上面的文字中,我需要找一个特定模式字符串" [x.xx.xx]"出错。

在上述情况下,他们发生了2次。

第一个是[4.01.070],第二个是[4.01.072]

我想要输出,如下所示:

发现了2次:

第一次出现:

名称: 4.01.070 内容:

 It must be possible for a user logged into a named XXXXXX project, 
    to have all user information and all granted user roles displayed in a simple way. 
    An example of the displayed information is displayed below:

User Name: XXXX
Full Name: XXXXX XXXX
e-Mail: XXXX@XXXXXX.com
Status: Active
Deactivation Date: 23 Marts 2028
Granted User Roles:     
    Test Case Author
    Requirement Author
Release manager
Description:
  Please note this user was trained in XXXXX in spring 1903.

第二次发生:

姓名:4.01.072

内容:

User Name: XXXX
Full Name: XXXXX XXXX
e-Mail: XXXX@XXXXXX.com
Status: Active
Deactivation Date: 23 Marts 2028
Granted User Roles:     
    Test Case Author
    Requirement Author
Release manager
Description:
  Please note this user was trained in XXXXX in spring 1903.

请告知。

此致 斯里里

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来匹配"标题"然后从你得到的位置推导出文本内容。

假设您的输入文本存储在变量s中,那么:

Dim re As Object
Dim dict As Object
Dim offset As Long
Dim hit As Object
Dim key As Variant
Dim results As Object

Set dict = CreateObject("Scripting.Dictionary")
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = "\[\d\.\d\d\.\d\d\d\]|$"
offset = -1
Set results = re.Execute(s)
For Each hit In results
    If offset >= 0 Then dict.Add key, Trim(Mid(s, offset, hit.FirstIndex - offset))
    offset = hit.FirstIndex + 1 + Len(hit.Value)
    key = hit.Value
Next

' Output - just to show what you have collected:
For Each key In dict.Keys
    Debug.Print key  '      [d.ddd.dd]
    Debug.Print dict(key) ' corresponding text
Next