2013-07-03 62 views
0

我需要導出到文件在一個特定的格式,目前我只導出查詢作爲一個Excel文件中的列:訪問導出文件,將行

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qryReport", "path" & "name.xls"

至極導致Excel文件是這樣的:

Name,Age,Sex 
Bob,47,M 
Janet,30,F 
William,23,M 

qryReport是一個簡單的選擇查詢。
現在我需要它導出的格式不同,它應該是每個文件只有一個記錄,是這樣的:現在

_begin_file_ 
name=Bob 
Age=47 
Sex=M 

的列行。 我在想重寫查詢作爲像這樣

Select "name=" & name as "_begin_file_" from clients 
Where name = [whatever] UNION ALL 
Select "Age=" & age as "_begin_file_" from clients 
Where name = [whatever] UNION ALL 
Select "Sex=" & sex as "_begin_file_" from clients 
Where name = [whatever] 

他們會每一次導出一個記錄。
有沒有更好的方法?

+0

你說的是每個從qryReport行創建單獨的文本文件? – HansUp

+0

你不能在你的'SELECT'中做這個。您需要在VBA代碼中執行此操作,逐行循環查詢結果。 –

+0

@HansUp是的,超出我的控制。 – FilipeG

回答

1

如果你有50條記錄,你想創建50個文本文件呢?太瘋狂了。 讓我們創建一個按鈕單擊事件可能help.Let說你還導出到Excel

Private Sub CommandExport_Click() 
Dim db As Database 
Dim rec1 As Recordset 
Dim xlFile As Object 
Dim xlWorkBook As Object 
Dim xlActiveWkb As Object 
Dim xlActiveSheet As Object 
Dim Col As Integer 

Set db = CurrentDb 
Set xlFile = CreateObject("Excel.Application") 
Set xlWorkBook = xlFile.Workbooks.Add 
Set xlActiveWkb = xlFile.Application.ActiveWorkBook 

xlFile.Visible = True 
xlActiveWkb.Sheets.Add 
xlActiveWkb.Worksheets(1).Name = "Test" 

Set xlActiveSheet = xlActiveWkb.Worksheets("Test") 
Set rec1 = db.OpenRecordset("clients") 

rec1.MoveFirst 
Col = 1 
while not rec1.eof 
    xlActiveSheet.Cells(1, Col).Value = "_begin__file_" 
    xlActiveSheet.Cells(2, Col).Value = "Name=" & rec1![Name] 
    xlActiveSheet.Cells(3, Col).Value = "Age=" & rec1![Age] 
    xlActiveSheet.Cells(4, Col).Value = "Sex=" & rec1![Sex] 
    Col =Col +1 
    rec1.MoveNext 
wend 

Set xlSheet = Nothing 
Set xlWorkBook = Nothing 
Set xlActiveWkb = Nothing 
rec1.Close 
db.Close 
Set rec1 = Nothing 
Set db = Nothing 
End Sub 
+0

是的,問題是它必須是每個記錄的一個文件,每個記錄有36個需要進入的字段。我無法控制它。我只是需要「翻轉」欄目,但我想知道是否有更好的方式來完成我提出的問題。感謝這個例子,這非常有用! – FilipeG