overwrite a csv file using vba - vba

There are a number of similar posts but nothing that does exactly what I want as simply as it needs to be for me to understand
I want to use Access 2007 VBA to open a csv file and replace the column headings row ie:
OldColumn1,OldColumn2
1,2
with
NewColumn1,NewColumn2
1,2
ie without disturbing the rump of data.
Then save and close.
I have tried this code, but it deletes my data:
Sub WriteFile()
Dim OutputFileNum As Integer
Dim PathName As String
PathName = Application.ActiveWorkbook.Path
OutputFileNum = FreeFile
Open PathName & "\Test.csv" For Output Lock Write As #OutputFileNum
Print #OutputFileNum, "NewCol1" & "," & "NewCol2"
Close OutputFileNum
End Sub

Import or link to the .csv so that you have the recordset in your Access 2007 databases.
Write a query with NewColumn[x] as an alias for OldColumn[x].
Write vba code to use TransferText functionality or make a macro to do the same to export your query as a .csv file (overwriting the original csv if you want/need).
Obviously, there are plenty of bonus things you could do to automate and reproduce this concept for any number or types of files. But the above solution should work in an all MS Access environment.
Let me know if you would like details on any of these steps.

Further to my earlier comment, please see the method which uses the Excel reference:
Public Sub EditCsv()
Dim xlApp As Object
dim xlWbk As Object
Dim xlWst As Object
Set xlApp = CreateObject("Excel.Application")
Set xlWbk = xlApp.Workbooks.Open ".../Test.csv" 'Amend this to your needs
Set xlWst = xlWbk.Sheets(1)
'This assumes the columns are at the beginning of the file
xlWst.Range("A1") = "My New Column Name"
xlWst.Range("B1") = "My New Second Column Name"
xlWbk.Close -1 'Close and save the file here
xlApp.Quit
Set xlApp = Nothing
Set xlWbk = Nothing
Set xlWst = Nothing
End Sub

Related

Exporting excel worksheet into ms access table

How can I import an excel worksheet into an MS Access table every time new data is added to the worksheet? Meaning every time I update my excel worksheet it would automatically update the ms access table?
I searched the internet and it seems there are several ways that it can be done, however I can't find a method that does exactly what I want. What I have so far isn't working nor does it do what I want it to do in the end. However, it is a start.
As I said I want vba to continuously update my access table through the excel worksheet. Right now the code isn't working. It keeps saying "path not found."
I tried debugging, but I haven't been able to figure out what was wrong with the path. This is what I have so far. Any suggestions on how to fix my code and or any suggestions for an easier way?
Sub ExportToAccess()
Dim oSelect As Range, i As Long, j As Integer, sPath As String
Sheet1.Activate
Set oSelect = Application.InputBox("Range", , Range("A1").CurrentRegion.Address, , , , , 8)
Dim oDAO As DAO.DBEngine, oDB As DAO.Database, oRS As DAO.Recordset
ChDir ActiveWorkbook.Path
sPath = Application.GetOpenFilename("Access * test.accdb\")
If sPath = "False" Then Exit Sub
Set oDAO = New DAO.DBEngine
Set oDB = oDAO.OpenDatabase(sPath)
Set oRS = oDB.OpenRecordset("ImportedData")
For i = 2 To oSelect.Rows.Count
oRS.AddNew
For j = 1 To oSelect.Columns.Count
oRS.Fields(j) = oSelect.Cells(i, j)
Next j
oRS.Update
Next i
oDB.Close
If MsgBox("Open the table?", vbYesNo) = vbYes Then
Dim oApp As Access.Application
Set oApp = New Access.Application
oApp.Visible = True
oApp.OpenCurrentDatabase sPath
oApp.DoCmd.OpenTable "ImportedData", acViewNormal, acReadOnly
oApp.DoCmd.GoToRecord , , acLast
DoEvents
End If
End Sub
Problem solved:
Though the method I used to solve my problem worked for me it might not be what most people would be expecting when seeing this post, however I still think it could be useful to some. Even though the solution I came up with is very simple. Instead of directly writing some code to transfer the data in my worksheet to an access table I simply had my vba code copy and paste the data that was entered into worksheet 1 then paste it into worksheet 2, then I linked worksheet 2 to an access table using the external data import function in access.

VBA save Excel file as .xls from Access

Hi, I have to perform Import from Excel file into Access DB, without duplicates. Only way that this can be done is by creating table where you can Import Excel data, and then append It to destination table by buiilding a Query. Problem is that this Excel file has to be .xls format, none other format is working for me (don't know why). How can I do that from Access - desirable without opening Excel workbook, just change It's extension file name ? This is what I tried (I receive error : " object doesn't support this property or method")
Dim XFile As Excel.Application
Set XFile = CreateObject("Excel.Application")
XFile.Workbooks.Open "C:\Users\Mike\Desktop\Copy.xlsx", True
XcelFile.SaveAs Filename:="C:\Users\Mike\Desktop\Copy.xlsx", FileFormat:=56
XFile.Workbooks.Close
End Sub
As you see, I need to save from .xlsx, It's default format for Excel 2013.
Any help much appreciated !!
Thanks #Porcupine911, that worked, even without opening workbook :)
Dim XcelFile As Excel.Application
Dim wb As Excel.Workbook
Set XcelFile = New Excel.Application
Set wb = XcelFile.Workbooks.Open("Filepath here")
wb.SaveAs Filename:="Filename here, with different destination and desirable extension", FileFormat:=56
wb.Close
Set XcelFile = Nothing
End Sub

Using excel as inputfile in vba (scripting - non MS OFFICE)

I'm developing a script in VBA (inside a workspace, not MS office program) that needs to use a small excel file as input. I want to use the data in the excel file and load it into a 2D array so that I can make decisions within my script based on this data.
I've tried to google this problem but generally I find problems within excel, but I haven't had any luck finding anything for vba scripting outside MS office.
Can I just use a .Xlsx as inputfile?
How do I put this data into a 2d array? My file only has 11 rows & 2 columns.
Thank you for your time.
This is confusing. VBA = MS Office VBA, as far as I know. Do you mean VB.NET? VBS? Anyway, to extract data from an xlsx file without opening it in Excel, you either need to unzip it and dig through the XML files inside, or use Office Open XML SDK or any other package like that.
Open XML SDK
Office Open XML fileformat
I think this will also work for Visual Basic [for Applications]; I tried it in Excel VBA and Word VBA:
In VBA Development Environment, select Tools, References. In the list that now appears, check the Object Model you need. In your case you will want to check the Microsoft Excel 12.0 Object Library.
You now have access to the complete Excel Object Model in your application and can open and manipulate an Excel spreadsheet file as you need.
The following code in VB for Word opens an Excel Spreadsheet and gets the value of the first cell:
Sub ExcelTestInWord()
Dim oExcel As Object
Dim wb As Object
Dim v
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim vrtSelectedItem As Variant
Set oExcel = CreateObject("Excel.Application")
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
If (fd.Show = -1) Then
For Each vrtSelectedItem In fd.SelectedItems
Set wb = oExcel.Workbooks.Open(vrtSelectedItem)
v = wb.Sheets(1).Cells(1).Value
wb.Close
Next vrtSelectedItem
End If
End Sub
Consider the VBScript code below as an example, save it as .vbs file to launch:
Option Explicit
Dim strSourceFilePath, strSourceSheetName, strSourceRange, arrData, strResult, i, j
' set initial data
strSourceFilePath = "C:\Test\data.xlsx"
strSourceSheetName = "input"
strSourceRange = "A1:B11"
' get 2-dimensional array from Excel sheet
With CreateObject("Excel.Application")
.Visible = False
.DisplayAlerts = False
With .Workbooks.Open(strSourceFilePath)
arrData = .Sheets(strSourceSheetName).Range(strSourceRange).Value
.Close
End With
.Quit
End With
' array output for debug purposes
strResult = ""
For j = 1 To UBound(arrData, 1)
For i = 1 To UBound(arrData, 2)
strResult = strResult & arrData(j, i) & ";" & vbTab
Next
strResult = strResult & vbCrLf
Next
WScript.Echo strResult

MS Access VBA convert query output to Excel format but not saving anywhere

I've been trying to use transfer spreadsheet methods but they appear to require an output path.
I just need to find out how to take a given query and simply "open up" an Excel file that contains the query output. I don't need the file actually saved anywhere.
You can open up your file without saving it by creating an Excel instance (or grabbing an existing one) and using the CopyFromRecordset function of the Excel.Range object.
This assumes your data are in an ADO recordset. You need to have references to Microsoft Excel XX.0 Object Library and Microsoft ActiveX Data Objects X.X Library` (if you are using ADO. If you use DAO then use whatever DAO reference you need)
I use this to grab an an Excel app or create a new one is Excel is not open already. I use WasANewInstanceReturned to figure how I need to clean up the Excel resources at the end. (Obviously I don't want to quit Excel if it is being use by something else).
Function GetExcelApplication(Optional ByRef WasANewInstanceReturned As Boolean) As Excel.Application
If ExcelInstanceCount > 0 Then
Set GetExcelApplication = GetObject(, "Excel.Application")
WasANewInstanceReturned = False
Else
Set GetExcelApplication = New Excel.Application
WasANewInstanceReturned = True
End If
End Function
Then grab that instance
Dim ApXL As Excel.Application, WasANewInstanceReturned as Boolean
Set ApXL = GetExcelApplication(WasANewInstanceReturned)
Add a workbook
Dim wbExp As Excel.Workbook
Set wbExp = ApXL.Workbooks.Add
Grab the first sheet
Dim wsSheet1 As Excel.Worksheet
Set wsSheet1 = wbExp.Sheets(1)
Put your recordset's field names in the first row
Dim fld As ADODB.Field
Dim col As Integer
col = 1
With wsSheet1
For Each fld In rst.Fields
.Cells(1, col).Value = fld.Name 'puts the field names in the first row
End With
col = col + 1
Next fld
End With
Then move the data just below the field names
wsSheet1 .Range("A2").CopyFromRecordset rst
Voila! You have an excel file open, with your data that has not been saved anywhere!
I usually set ApXL.ScreenUpdating = False before doing any of this and ApXL.ScreenUpdating = True at the end.
I'll let you stitch this together for your needs.
The file must be saved somewhere for Excel to open it.
If the dataset is small enough, you can use copy/paste (no file here). Otherwise, just use the %TEMP% folder for the file location.
Edit:
One simple way to get the TEMP folder is to use =Environ("TEMP")
I open and export a query from access to excel. First I created a worksheet in excel and saved it. Then I created a module in the vba part of Access (2013):
Option Compare Database
' Testtoexporttoexcel'
Function ExportQuerytoExcel()
On Error GoTo ExportQuerytoExcel_Err
' Exports the query to excel to a sheet named Nameofyoursheet
DoCmd.TransferSpreadsheet acExport, 10, "nameofyourquery", "yourPath:\nameofyourworkbook", False, "Nameofyour worksheet"
ExportQuerytoExcel_Exit:
Exit Function
ExportQuerytoExcel_Err:
MsgBox Error$
Resume ExportQuerytoExcel_Exit
End Function
-----then add another function that says:
Option Compare Database
Function OpenExcelFromAccess()
'Opens Excel to the chart
Dim MYXL As Object
Set MYXL = CreateObject("Excel.Application")
With MYXL
.Application.Visible = True
.workbooks.Open "Yourpath:\nameofyourworkbook"
End With
'Application.Quit
End Function
hope this helps, this is my first time answering a question.
Aloha

Opening and Excel file in Access using VBA and saving it to a different name and closing it properly

I have been searching for some time on how exactly to go about this, but I keep coming up with a large number of possible ways that come close, but never really give me exactly the sort of thing I'm looking for. The concept is pretty simple I need to open a certian .xls file using some VBA code in Access 2010. Once the file is opened I need to insert data and do some things to the file then save the file as a different filename and close the file. I also need it to close excel if it was not already open and if it was open I need it to leave excel alone and not save/close anything other than the template.xls file I am working with. I currently have code that will do part of this provided Excel is not already open at the time the script runs. When excel is already opened I get the following error;
"Run-time'91': Object variable or With block variable not set."
When I click debug I get the following line highlighted
x.ActiveWorkbook.SaveAs fileName:=savedfilename
Here is the code without all the junk that doesn't relate to the issue. I have cobbled together using examples from various sites.
Dim DateSampled As String
Dim strPath As String
Dim TemplatePath As String
Dim x As Excel.Application
Dim xBook As Excel.Workbook
Dim xSheet As Excel.Worksheet
DateAsString = Format(DateSampled, "MMDDYYYY")
savedfilename = strPath & "\" & TrainNum & "-" & DateAsString & ".xls"
TemplatePath = "B:\template.xls"
Set x = CreateObject("Excel.Application")
x.Visible = False
Set xBook = GetObject(TemplatePath)
xBook.Windows(1).Visible = True
Set xSheet = xBook.Worksheets(1)
'---------------CODE DOES STUFF WITH THE FILE -----------------------
x.DisplayAlerts = False
x.ActiveWorkbook.SaveAs fileName:=savedfilename
x.DisplayAlerts = True
x.ActiveWorkbook.Close
Set x = Nothing
Set xBook = Nothing
Set xSheet = Nothing