في هذه الحالة ، سنقوم باستعمال مصفوفة بسيطة على سبيل المثال لتحديد الإستعلامات التي موجودة لديك ، كالتالي :-
Sub ExportQueriesToExcel()
Dim xlApp As Object
Dim xlWorkbook As Object
Dim xlWorksheet As Object
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim queryNames As Variant
Dim sheetIndex As Integer
Dim filePath As String
Dim colIndex As Integer
Dim rowIndex As Integer
queryNames = Array("Qallmsr2", "Qallshm2", "Qallshy2", "Qalltipr2")
filePath = Application.CurrentProject.Path & "\تقرير_الاكسيل.xlsx"
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Add
Set db = CurrentDb
sheetIndex = 1
For Each queryName In queryNames
Set rs = db.OpenRecordset(queryName, dbOpenSnapshot)
If sheetIndex <= xlWorkbook.Sheets.Count Then
Set xlWorksheet = xlWorkbook.Sheets(sheetIndex)
Else
Set xlWorksheet = xlWorkbook.Sheets.Add
End If
xlWorksheet.Name = queryName
colIndex = 1
For Each fld In rs.Fields
xlWorksheet.Cells(1, colIndex).Value = fld.Name
xlWorksheet.Cells(1, colIndex).Font.Bold = True
colIndex = colIndex + 1
Next fld
rowIndex = 2
Do While Not rs.EOF
colIndex = 1
For Each fld In rs.Fields
xlWorksheet.Cells(rowIndex, colIndex).Value = fld.Value
colIndex = colIndex + 1
Next fld
rowIndex = rowIndex + 1
rs.MoveNext
Loop
rs.Close
sheetIndex = sheetIndex + 1
Next queryName
xlWorkbook.SaveAs filePath
xlWorkbook.Close
xlApp.Quit
Set rs = Nothing
Set db = Nothing
Set xlWorksheet = Nothing
Set xlWorkbook = Nothing
Set xlApp = Nothing
MsgBox "تم تصدير البيانات بنجاح", vbInformation + vbMsgBoxRight, "نجاح العملية"
End Sub
test.accdb