访问导出文件,列到行

时间:2013-07-03 16:53:26

标签: sql vba ms-access

我需要以特定格式导出文件,目前我只是将查询导出为ex​​cel文件:

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]

他们每次会输出一条记录吗 还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

如果你有50条记录,你想创建50个文本文件怎么办?太疯狂了。 让我们创建一个可能有帮助的按钮单击事件。假设您仍然导出到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