Sorting strings in word macro

喜夏-厌秋 提交于 2019-12-24 09:03:44

问题


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"

I will need them listed as

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

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...


回答1:


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


来源:https://stackoverflow.com/questions/16683164/sorting-strings-in-word-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!