Hi,
I use the code below to loop through a table and export data to a named range in almost 100 different spreadsheets. These are identical in all but the filename, which changes by record.
It works fine if I manually open all the sheets first and clear the ranges in all of them, but otherwise I get a "Cannot expand named range" error.
Is it possible to clear each named range first? If so, can you tell me the code for that?
I'm no programmer and it took me long enough to figure out the DoCmd.TransferSpreadsheet part!
I'm using Access and Excel 2010.
Thanks
I use the code below to loop through a table and export data to a named range in almost 100 different spreadsheets. These are identical in all but the filename, which changes by record.
It works fine if I manually open all the sheets first and clear the ranges in all of them, but otherwise I get a "Cannot expand named range" error.
Is it possible to clear each named range first? If so, can you tell me the code for that?
I'm no programmer and it took me long enough to figure out the DoCmd.TransferSpreadsheet part!
I'm using Access and Excel 2010.
Thanks
Code:
DoCmd.SetWarnings False
Dim MyFilename As String ' Value will be set repeatedly in the loop
Dim rs As DAO.Recordset
Dim strSql As String
strSql = "SELECT [CRN-WM Trusts].ODSCode, [CRN-WM Trusts].Trust FROM [CRN-WM Trusts] WHERE ((([CRN-WM Trusts].Type)='Trust') AND (([CRN-WM Trusts].Current)=True))ORDER BY [CRN-WM Trusts].Trust;"
Set rs = CurrentDb.OpenRecordset(strSql)
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
Me.lstTrusts.Value = rs.Fields("ODSCode")
MyFilename = DLookup("[Trust]", "CRN-WM Trusts", "[ODSCode]=[Forms]![frmMenu]![lstTrusts]") & " - Recruitment and ABF.xlsx"
DoCmd.OpenQuery "Trust 002 Monthly recruits - part 2 - make table" 'this year
DoCmd.OpenQuery "Trust 005 Monthly recruits - part 2 - make table" 'last year
[COLOR="Red"] ' Code here, to clear the named range first?[/COLOR]
DoCmd.TransferSpreadsheet TransferType:=acExport, SpreadsheetType:=acSpreadsheetTypeExcel9, TableName:="Trust 009a Recruitment only", FileName:="G:\Database\Trust Reports\Weekly Reports\" & MyFilename, Range:="Trust009a"
.MoveNext
Wend
End If
.Close
End With
Set rs = Nothing
DoCmd.SetWarnings True
End Sub