Try this....
I'm not real happy with this code creating, then deleting a query, but it creates the Excel workbooks.
You could create a saved query "TempQuery" and modify the code to NOT create/delete it, just keep changing the query SQL.
Code:
Private Sub managerquery()
Const strTemp = "TempQuery" ' or whatever you like
Dim dB As DAO.Database
Dim managerinfo As DAO.Recordset
Dim affiliateinfo As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim sqlstr As String
Dim strFileName As String
Set dB = CurrentDb
sqlstr = "SELECT DISTINCT tbl_affiliates.Manager FROM tbl_affiliates ORDER BY tbl_affiliates.Manager; "
Set managerinfo = dB.OpenRecordset(sqlstr)
If (managerinfo.BOF And managerinfo.EOF) Then
' If (mgrRec.RecordCount = 0) Then
MsgBox ("No records found on tbl_activeAccts, import was empty or failed")
Exit Sub
Else
managerinfo.MoveLast
managerinfo.MoveFirst
Do While Not managerinfo.EOF
sqlstr = "SELECT tbl_affiliates.username, tbl_affiliates.manager "
sqlstr = sqlstr & " FROM tbl_affiliates"
sqlstr = sqlstr & " WHERE tbl_affiliates.manager = '" & managerinfo.Fields("Manager") & "'"
sqlstr = sqlstr & " ORDER BY tbl_affiliates.username;"
' Debug.Print sqlstr
Set affiliateinfo = dB.OpenRecordset(sqlstr)
If (affiliateinfo.BOF And affiliateinfo.EOF) Then
' If (affilateinfo.RecordCount = 0) Then
MsgBox ("No records found on tbl_activeAccts, import was empty or failed")
Exit Do
Else
' Create a new temporary query with the modified SQL string
Set qdf = dB.CreateQueryDef(Name:=strTemp, SQLText:=sqlstr)
'Change to your path
strFileName = "C:\users\e99714\desktop\" & managerinfo.Fields("manager") & ".xlsx"
' strFileName = "D:\Misc\" & managerinfo.Fields("manager") & ".xlsx" ' <<-- for my testing
'Syntax: DoCmd.TransferSpreadsheet(TransferType, SpreadsheetType, TableName, FileName, HasFieldNames, Range, UseOA)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, strTemp, strFileName, True
'for acSpreadsheetTypeExcel12Xml parameter see: -->> https://docs.microsoft.com/n-us/office/vba/api/access.acspreadsheettype
'delete temp query
dB.QueryDefs.Delete strTemp
End If
affiliateinfo.Close
managerinfo.MoveNext
Loop
End If
Msgbox "Done!!"
'clean up
On Error Resume Next
affiliateinfo.Close
managerinfo.Close
Set managerinfo = Nothing
Set affiliateinfo = Nothing
Set dB = Nothing
End Sub