I\'m working within MS Access 2013 on Windows 10 and I\'m simply trying to write a Sub that opens an Excel file on disk, changes the column formatting and some columns, save
Declare and use a specific Workbook object - as you do for Worksheet and Range, like this:
Dim xls As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Range
Set xls = New Excel.Application
Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
Set wks = wkb.Worksheets(1)
Set rng = wks.Range()
' Do stuff.
wks.Name = "My New Name"
With rng
' Do more.
End With
wkb.Close True
Set rng = Nothing
Set wks = Nothing
Set wkb = Nothing
xls.Quit
Set xls = Nothing
Also, don't use Select, that's for visible use only. Define ranges instead.
Cinetyk's EDIT:
Using @Gustav 's indications, the code that does what I wanted and solves the problem is:
Sub changeXLcolumnFormatting()
Dim XL As Excel.Application
Dim sht As Excel.Worksheet
Dim wkb As Excel.Workbook
Dim rng As Range
Set XL = New Excel.Application
XL.Visible = False
XL.DisplayAlerts = False
Set wkb = XL.Workbooks.Open("C:\Users\640344\Desktop\rawDataTest.XLSX")
Set sht = wkb.Worksheets(1)
Dim i As Integer, j As Integer
field_names = Split("datasistema|Data de Registo|Data Registo CMVM", "|")
end_of_table = sht.UsedRange.Columns.Count
For j = 0 To UBound(field_names)
For i = 1 To end_of_table
Set rng = sht.Cells(1, i)
If InStr(rng.Text, field_names(j)) > 0 Then
sht.Columns(i).NumberFormat = "yyyy-mm-dd HH:MM:ss"
End If
Next i
Next j
wkb.Close (True)
Set rng = Nothing
Set sht = Nothing
XL.Quit
Set XL = Nothing
End Sub