在单词宏中排序字符串

时间:2013-05-22 03:50:07

标签: ms-word word-vba

我需要帮助编写一个函数,它将获取一个字符串数组,并根据字符串中的数字字符(升序)将其排序为一个新的字符串数组? 说我有以下字符串数组:

"abc53ddd", "2zzz2yyy", "14"

我需要将它们列为

"14", "2zzz2yyy" and "abc53ddd"

字符串中的数字字符为14, 22 and 53. 我可以将字符串剥离到数字部分并对数组进行排序,但我无法恢复剩余的字符以按正确的顺序列出它们...

1 个答案:

答案 0 :(得分:0)

将ADO与断开连接的记录集一起使用。见http://technet.microsoft.com/en-us/library/ee176578.aspx。它快速而强大。恕我直言,这是最好的。

'recordset definition
Dim rst As New ADODB.Recordset 'must be reference "Microsoft ActiveX Data Objects"
'OR use automation (without reference)
'Dim rst
'Set rst = CreateObject("ADOR.Recordset")

'fields definition - how many you want (name, type, lenght)
rst.Fields.Append "field1", ADODB.DataTypeEnum.adVarChar, 255
rst.Fields.Append "number", ADODB.DataTypeEnum.adInteger

rst.Open

'add values, for example:
Dim rc As ADODB.Record
rst.AddNew "field1", "abc53ddd"
rst.AddNew "field1", "2zzz2yyy"
rst.AddNew "field1", "14"

'make numbers from string and store in field [number]
Dim reg As New RegExp
'OR
'Set reg = CreateObject("vbscript.regexp")
reg.Pattern = "\D" 'non-digit
reg.Global = True

rst.MoveFirst
Do Until rst.EOF
    rst!Number = Val(reg.Replace(rst!field1, "")) 'delete non-digit
    rst.MoveNext
Loop

'sort!
rst.Sort = "number ASC" 'sort by field1 ascending

'show output
rst.MoveFirst
Do Until rst.EOF
    Debug.Print rst!field1, rst!Number
    rst.MoveNext
Loop