在Access中按字母顺序排列逗号分隔的字符串

时间:2013-08-21 14:15:42

标签: vba ms-access access-vba

我不太确定从哪里开始,我有一小段代码循环遍历表并将所有字段名称写入字符串以用作组合框中的值rowsource。我希望这些项目按字母顺序排列,但我不太确定使用字符串变量(或在组合框RowSource属性中)执行此操作的最佳方法。

有关最佳方法的任何想法或建议吗?

如果它有用,我的代码是:

Dim strFields As String
Dim fldTemp As Field
Dim intCount As Integer
Dim setData As DAO.Recordset

Set setData = CurrentDb.OpenRecordset("SELECT * FROM tblEnvironment WHERE 1 = 2")

For Each fldTemp In setData.Fields
    strFields = strFields & ", " & fldTemp.Name
Next

strFields = Mid(strFields, 3)

For intCount = 1 To 10
    Controls("cboField" & intCount).RowSource = strFields
Next

StrFields是我想要进行alphabatize的。提前谢谢!

2 个答案:

答案 0 :(得分:3)

我会将您正在创建的字符串转换为数组,然后对该数组进行排序。然后,您可以使用Join将数组转换为逗号分隔的字符串

使用找到here的冒泡排序,这就是我要将您的代码调整为

Dim strFields As String
Dim fldTemp As Field
Dim intCount As Integer
Dim setData As DAO.Recordset
Dim FieldList() As String ' array to hold field names

Set setData = CurrentDb.OpenRecordset("SELECT * FROM tblEnvironment WHERE 1 = 2")

intCount = 0
For Each fldTemp In setData.Fields
    ReDim Preserve FieldList(intCount + 1) ' expand the array for each field name
    FieldList(intCount) = fldTemp.Name
    intCount = intCount + 1
Next

BubbleSort FieldList 'sort the fieldnames

strFields = Join(FieldList, ",") 'join the names together with commas
strFields = Mid(strFields, 3)

For intCount = 1 To 10
    Controls("cboField" & intCount).RowSource = strFields
Next

bubblesort代码,只是在链接腐烂的情况下:

Sub BubbleSort(arr)
  Dim strTemp As String
  Dim i As Long
  Dim j As Long
  Dim lngMin As Long
  Dim lngMax As Long
  lngMin = LBound(arr)
  lngMax = UBound(arr)
  For i = lngMin To lngMax - 1
    For j = i + 1 To lngMax
      If arr(i) > arr(j) Then
        strTemp = arr(i)
        arr(i) = arr(j)
        arr(j) = strTemp
      End If
    Next j
  Next i
End Sub

答案 1 :(得分:1)

如果从strFields创建字符串数组,则可以使用WizHook.SortStringArray对数组进行排序。我在下面添加了SortStringArray演示程序。

您可以在代码中使用SortStringArray,就像这样......

Dim astrFields() As String
astrFields = Split(strFields, ", ")
WizHook.SortStringArray astrFields

如果你再次需要它作为一个字符串......

strFields = Join(astrFields, ", ")

也许你可以走过阵列......

For intCount = 0 To UBound(astrFields)
    Debug.Print intCount, astrFields(intCount)
Next

有关WizHook的信息很吓人。当我探索SortStringArray谜团时,我为其WizHook方法创建了此示例程序。

Public Sub WizHook_SortStringArray()
   ' The WizHook Key is not required for this procedure.
   'WizHook.Key = 51488399
    Dim a(3) As String
    Dim i As Long
    a(0) = "zulu"
    a(1) = "alpha"
    a(2) = "gamma"
    a(3) = "delta"
    WizHook.SortStringArray a
    For i = 0 To 3
        Debug.Print a(i)
    Next i
End Sub

我在该程序的原始版本的评论中添加了。某些WizHook方法需要Key值。但是,我不相信SortStringArray。如果它无法正常工作,请尝试启用WizHook.Key行。