2010-05-17 618 views

回答

3

您應該問問自己,您是否需要一個通用解決方案(another is by Allen Browne)或者您是否僅僅爲了目的需要。如果你真的只需要這一次,那就用簡單的方法吧。

在附註中,當連接VBA代碼中的列表時,利用長期訪問專家Trevor Best教給我的一個技巧,那就是將分隔符粘貼到每個值的開頭,然後使用Mid( )將其剝離。取而代之的是你的遍歷子記錄內:

If Len(strOutput) = 0 Then 
    strOutput = NewValue 
    Else 
    strOutput = strOutput & ", " & NewValue 
    End If 

...使用內循環:

strOutput = strOutput & ", " & NewValue 

...然後當你退出循環,剝去領先分隔符:

strOutput = Mid(strOutput, 3) 

這影響了整個地方,簡化了大量上下文連接的代碼。

1

編號訪問權限沒有GROUP_CONCAT功能。但是,可以創建一個VBA函數,它可以讓你傳遞一個包含SQL語句的字符串並獲得相應的功能(不是我推薦它,但它是可能的)。

以我個人的Wayback機器,這裏是一些代碼,我回了信,當恐龍統治地球:

Public Function ListQuery(SQL As String _ 
          , Optional ColumnDelimiter As String = " " _ 
          , Optional RowDelimter As String = vbCrLf) As String 
'PURPOSE: to return a combined string from the passed query 
'ARGS: 
' 1. SQL is a valid Select statement 
' 2. ColumnDelimiter is the character(s) that separate each column 
' 3. RowDelimiter is the character(s) that separate each row 
'RETURN VAL: 
'DESIGN NOTES: 

Const PROCNAME = "ListQuery" 
Const MAXROWS = 100 
Const MAXCOLS = 10 
Dim oConn As ADODB.Connection 
Dim oRS As ADODB.Recordset 
Dim oField As ADODB.Field 
Dim sRow As cString 
Dim sResult As cString 

On Error GoTo ProcErr 

Set sResult = New cString 
Set sRow = New cString 
Set oConn = GetADOConn() 

sResult.Clear 
Do Until oRS.EOF 
    sRow.Clear 

    For Each oField In oRS.Fields 
     With sRow 
      If .Length > 0 Then 
       .Append ColumnDelimiter 
      End If 

      .Append Nz(oField.Value) 
     End With 
    Next oField 

    sRow.Trim 
    If sRow.Length > 0 Then 
     With sResult 
      .Append sRow 
      .Append RowDelimter 
     End With 
    End If 

    oRS.MoveNext 
Loop 
oRS.Close 
oConn.Close 

With sResult 
    If .Right(Len(RowDelimter)).Value = RowDelimter Then 
     .Length = .Length - Len(RowDelimter) 
    End If 
End With 

FunctionResult: 
    ListQuery = sResult.Value 

CleanUp: 
    Set sResult = Nothing 
    Set sRow = Nothing 
    Set oField = Nothing 
    Set oRS = Nothing 
    Set oConn = Nothing 

Exit Function 
ProcErr: 
    ' logging code... 
    Resume CleanUp 

End Function 

GetADOConn功能是獲取當前數據庫連接的集中功能。 cString是一類模仿.NET的StringBuilder類的行爲,但早在.NET就是TLD和營銷宣傳之外的東西。由於每行都會調用它,因此VBA的內置字符串連接將會很慢,因此需要類似StringBuilder類。原來的代碼(我已經部分修改過)對可以使用的行數和列數有一個限制,這就是常量的全部內容。

+0

在爲Access編寫代碼時,在DAO中編寫代碼似乎更有意義,因爲除了與SQL Server交互之外,ADO幾乎已經死亡。 – 2010-05-18 23:15:08

+0

@ David-W-Fenton - 嗯,有人可能會說DAO已經死了,但我理解你的觀點。該代碼很容易改變爲DAO。 IIRC,該代碼的日期是在97年的某個時候,所以可能是因爲我當時還在做ASP Classic的東西,所以我在Access中涉及ADO。 – Thomas 2010-05-19 00:50:42

+1

沒有辦法認爲DAO已經死了,因爲它是Access的一個積極開發的組件,在A2007和A2010中對ACE進行修改和改進。它是完全死掉的ADO經典,由ADO.NET取代,它不能在Access中使用(至少現在不是這樣)。 – 2010-05-20 00:50:32

相關問題