将 ADO 记录集文本字段排序为数字
使用 VBA,我有一组返回 ADODB.Recordset
的函数,其中所有列均为 adVarChar
。 不幸的是,这意味着数字被排序为文本。 因此 1,7,16,22 变为 1,16,22,7
是否有任何方法可以将数字作为文本列进行排序,而无需更改列的类型?
Sub TestSortVarChar()
Dim strBefore, strAfter As String
Dim r As ADODB.RecordSet
Set r = New ADODB.RecordSet
r.Fields.Append "ID", adVarChar, 100
r.Fields.Append "Field1", adVarChar, 100
r.Open
r.AddNew
r.Fields("ID") = "1"
r.Fields("Field1") = "A"
r.AddNew
r.Fields("ID") = "7"
r.Fields("Field1") = "B"
r.AddNew
r.Fields("ID") = "16"
r.Fields("Field1") = "C"
r.AddNew
r.Fields("ID") = "22"
r.Fields("Field1") = "D"
r.MoveFirst
Do Until r.EOF
strBefore = strBefore & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
r.Sort = "[ID] ASC"
r.MoveFirst
Do Until r.EOF
strAfter = strAfter & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
MsgBox strBefore & vbCrLf & vbCrLf & strAfter
End Sub
注意:我正在使用 Project 2003 和 Excel 2003 并引用 Microsoft ActiveX DataObject 2.8 Library
Using VBA i have a set of functions that return an ADODB.Recordset
where all the columns as adVarChar
. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7
Is there any methods that can sort numerics as text columns without resorting to changing the type of the column?
Sub TestSortVarChar()
Dim strBefore, strAfter As String
Dim r As ADODB.RecordSet
Set r = New ADODB.RecordSet
r.Fields.Append "ID", adVarChar, 100
r.Fields.Append "Field1", adVarChar, 100
r.Open
r.AddNew
r.Fields("ID") = "1"
r.Fields("Field1") = "A"
r.AddNew
r.Fields("ID") = "7"
r.Fields("Field1") = "B"
r.AddNew
r.Fields("ID") = "16"
r.Fields("Field1") = "C"
r.AddNew
r.Fields("ID") = "22"
r.Fields("Field1") = "D"
r.MoveFirst
Do Until r.EOF
strBefore = strBefore & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
r.Sort = "[ID] ASC"
r.MoveFirst
Do Until r.EOF
strAfter = strAfter & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
MsgBox strBefore & vbCrLf & vbCrLf & strAfter
End Sub
NB: I am using Project 2003 and Excel 2003 and referencing Microsoft ActiveX DataObject 2.8 Library
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
左填充零,其数量至少与最大数字位数相同。
例如
0001
0010
第0022章
1000
您可以使用 Right$() 来完成此操作。
Left pad with Zeros with at least as many as maximum number digits.
e.g.
0001
0010
0022
1000
You can use Right$() to accomplish this.
使用 Val() 函数对文本列进行数字排序。 例子:
Use the Val() function to sort numerically on a text column. Example: