1

我不太确定从哪里开始,我有一小段代码循环遍历一个表并将所有字段名称写入一个字符串,以用作组合框中的值行源。我希望这些项目按字母顺序排列,但不太确定使用字符串变量(或组合框 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 是我想要的字母。提前致谢!

4

2 回答 2

3

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

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

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

冒泡排序代码,以防链接失效:

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
于 2013-08-21T14:43:51.847 回答
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行。

于 2013-08-21T15:05:02.290 回答