在单词宏中对字符串进行排序 [英] Sorting strings in word macro

查看:122
本文介绍了在单词宏中对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数来获取帮助,该函数将接受字符串数组并将其仅基于字符串中的数字字符(升序)将其排序为新的字符串数组? 说我有以下字符串数组:

I need help with writing a function which will take an array of strings and sort this into a new array of strings based on only the number characters in the strings (ascending)? say I have the following array of strings:

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

我需要将它们列为

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

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

as the number characters in the string are 14, 22 and 53. I can strip the string into the number portions and sort the array but I can't recover the remaining characters to list them back in the right order...

推荐答案

对断开连接的记录集使用ADO.请参阅 http://technet.microsoft.com/en-us/library/ee176578. aspx .它既快速又强大.恕我直言,这是最好的.

Use ADO with disconnected recordset. See http://technet.microsoft.com/en-us/library/ee176578.aspx. It is fast and robust. IMHO, it is the best.

'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

这篇关于在单词宏中对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆