Question : Export Table and Exclude a field in the export

I would like to export a table into Excel and exclude a field from the table in the export (without using a query as te object type)  I was hping to use a SQL statement to define the fields to export rather than the table.

Is this possible?

Answer : Export Table and Exclude a field in the export

gpotenza,

Assuming that:
1) The table name is always the same
2) You have one column you want to exclude, and its name never changes

then try this.

Patrick
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
Sub ExportToExcel()
    
    ' uses late binding for Excel
    
    Dim rs AS DAO.Recordset
    Dim xlApp As Object
    Dim xlWb As Object
    Dim xlWs As Object
    Dim Counter As Long
    Dim ColNumber As Long
    
    Const SaveToPath As String = "c:\Results\Report_"
    Const SQL As String = "SELECT * FROM [SomeTable]"
    Const ColumnToDelete As String = "DeleteMe"
    
    Set rs = CurrentDb.OpenRecordset(SQL)
    
    ' instantiate Excel object
    
    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False
    Set xlWb = xlApp.Workbooks.Add
    Set xlWs = xlWb.Worksheets(1)
    With xlWs
        ' write recordset headings
        For Counter = 0 To rs.Fields.Count - 1
            .Cells(1, Counter + 1) = rs.Fields(Counter).Name
        Next
        .Cells(2, 1).CopyFromRecordset rs
        If xlApp.CountIf(.Range("1:1"), ColumnToDelete) > 0 Then
            ColNumber = xlApp.Match(ColumnToDelete, .Range("1:1"), 0)
            .Cells(1, ColNumber).EntireColumn.Delete
        End If
    End With
    
    ' Excel 2007/2010 requires the file format to be specified, so check
    ' for application version.  see for more info:
    ' http://www.dailydoseofexcel.com/archives/2006/10/29/saveas-in-excel-2007/
    
    If Val(xlApp.Version) < 12 Then
        xlWb.SaveAs SaveToPath & Format(Now, "yyyymmdd") & ".xls"
    Else
        ' to use XLSX format:
        xlWb.SaveAs SaveToPath & Format(Now, "yyyymmdd") & ".xlsx", 51
        ' or to use XLSM format:
        'xlWb.SaveAs SaveToPath & Format(Now, "yyyymmdd") & ".xlsm", 52
        ' or to use XLSB format:
        'xlWb.SaveAs SaveToPath & Format(Now, "yyyymmdd") & ".xlsb", 50
        ' or to use good old XLS format:
        'xlWb.SaveAs SaveToPath & Format(Now, "yyyymmdd") & ".xls", 56
    End If
    
    xlWb.Close False
    xlApp.DisplayAlerts = True
    Set xlWs = Nothing
    Set xlWb = Nothing
    xlApp.Quit
    Set xlApp = Nothing
    rs.Close
    Set rs = Nothing
 
    MsgBox "Done"
 
End Sub
Random Solutions  
 
programming4us programming4us