I am trying to add 3 additional fields with data on them to a .txt file during the import process. But I don't know how to do this. One of those fields would contain the date introduced in the Combo5 combobox. The other two, one would contain "Checked" and the other "ArticleN5".
Can anyone provide any instructions on how this can be achieved?
Thank you all in advance,
Hope you're all safe.
This is what I have so far:
Private Sub Command0_Click()
Dim Dates As String
Dim Path As String
Dates = Format(Me.Combo5, "yymmdd")
Path = "C:\Users\alex\Desktop\CGD\20200117\UCP" & Dates & "A_CGD.txt"
DoCmd.TransferText acImportFixed, "UCPYYMMDDA_CGD_SPECS", "teste", PATH, True
End Sub
Do the fields have to be added to the TXT file itself, or to the table where the file is imported to? If you just need to add the info to the fields in the table, you could open the table as a recordset after the TXT is imported and add the additional data.
Example:
Dim rsData as DAO.Recordset
Set rsData = currentDB.openrecordset("TableName", dbtable)
rsData.Movefirst
Do While not rsdata.eof
with rsdata
.edit
.field("FieldName") = "Checked"
.field("FieldName") = comboboxvalue
.field("FieldName") = value
.update
end with
rsData.MoveNext
rsdata.close
This should get you close
Related
I have a MS Access file and it has a form with a button which export a named query to a CSV file. When i open the CSV to Excel, a column with lengthy text with line breaks get cuts off. When i tried to copy and then paste special as CSV on the Excel it turns out to be fine.
Here is my VBA code
Public Sub exportQuery(exportSQL As String)
Dim db As DAO.Database, qd As DAO.QueryDef
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
Set db = CurrentDb
'Check to see if querydef exists
For i = 0 To (db.QueryDefs.Count - 1)
If db.QueryDefs(i).Name = "tmpExport" Then
db.QueryDefs.Delete ("tmpExport")
Exit For
End If
Next i
Set qd = db.CreateQueryDef("tmpExport", exportSQL)
'Set intial filename
fd.InitialFileName = "export_" & Format(Date, "mmddyyy") & ".csv"
If fd.Show = True Then
If Format(fd.SelectedItems(1)) <> vbNullString Then
DoCmd.TransferText acExportDelim, , "tmpExport", fd.SelectedItems(1), False
End If
End If
'Cleanup
db.QueryDefs.Delete "tmpExport"
db.Close
Set db = Nothing
Set qd = Nothing
Set fd = Nothing
End Sub
And this for command button to call the function
Private Sub Command0_Click()
Dim queryStr As String
'Store Query Here:
queryStr = "SELECT [Name],[Notes] FROM [GetListForUpload]"
Call exportQuery(queryStr)
End Sub
Can someone help me with this?
I solved my own problem haha! So i just want to share this for any other who stumbled from this situation. Their's this hidden system objects that you want to show up in navigation options. So first is you check to show the hidden system objects in the navigation options and you will see tables that is greyed out ex.(MSysIMEXColumns, MSysIMEXSpecs) then create a specification. Open the table MSysIMEXColumns, you will see all of the field names on the specification you've created. So on my part i have Notes column which contains lenghty texts with linebreaks. In the MsysIMEXColumns table, I changed the DataType for the fieldname Notes from 10 (Text) to 12 (Memo) and voila. No lenghty texts get cuts off or truncated anymore :)
PS: If you have more than 1 specifications created please identify the specid first from MSysIMEXSpecs and then check it in MSysIMEXColumns before you changed anything for not to get confused.
I'm pretty new to using VBA. I have an access database where the user clicks a button and this will upload multiple files.
The files uploaded are temp tables and get fields added to them etc. Once updates have been made to the temp tables, the records get transferred into a permanent table.
It uploads multiple files at once, so as files get uploaded the table they get input into tables called'temp_filename', with each file getting its own table.
Below is my code. For the alter table statement I want to upload the temp table which has just been created. As this table will be named something different every time I tried to assign it to a variable. I tried different syntax etc, however I keep getting errors. Can anyone see where I am going wrong? Any help would be appriciated.
Public Sub Import()
Dim oFileDiag As Office.FileDialog
Dim path As String: path = ""
Dim oFSO As New FileSystemObject
Dim FileSelected As Variant
Dim FileNameSelected As Variant
Dim UpdatedTableName As Variant
Set oFileDiag = Application.FileDialog(msoFileDialogFilePicker) ''Picks file to import
oFileDiag.AllowMultiSelect = True ''Allows multiple files to be selected
oFileDiag.Title = "Please select the reports to upload"
oFileDiag.Filters.Clear
oFileDiag.Filters.Add "Excel Spreadsheets", "*.xlsx, *.xls" ''Only allows xlsx and xls file types to upload
If oFileDiag.Show Then
For Each FileSelected In oFileDiag.SelectedItems
FileNameSelected = oFSO.GetFileName(FileSelected)
UpdatedTableName = "temp_" & FileNameSelected
If oFileDiag.SelectedItems.Count > 0 Then path = oFileDiag.SelectedItems(1)
If Len(path) > 0 Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, UpdatedTableName, path, 1
DoCmd.RunSQL "ALTER TABLE UpdatedTableName ADD COLUMN [Date_of_Report] TEXT(100);"
MsgBox "The " & FileNameSelected & " file has been uploaded"
Else
MsgBox "File not found"
End If
Next
End If
You need to concatenate the table name into the SQL string:
DoCmd.RunSQL "ALTER TABLE [" & UpdatedTableName & "] ADD COLUMN [Date_of_Report] TEXT(100);"
I've used square brackets just in case there are things like spaces in the table name.
Regards,
I have a browse button and pick and place the file name and path in textbox5. I need to use the same value in my file name but it does not work. It throws:
Run Time Error 2522- The action or method requires a File Name argument
Private Sub Command10_Click()
Dim dbs As DAO.Database
Dim td As DAO.TableDef
Dim fileName As String
'set current database
Set dbs = CurrentDb
Me.Text5 = fileName
DoCmd.TransferSpreadsheet acImport, , "tblS3DimportTemp", fileName, True
MsgBox "Data Uploaded!"
End Sub
Instead of: Me.Text5 = fileName
write:
fileName = Me.Text5
In many programming languages the left variable gets the value of the right one.
I'm working with someone who has to identify certain variables within excel files. Currently, the man I'm working with has a great deal of folders and sub-folders that have Excel documents in them. He's using a VBA code that looks within a folder for a sub-folder, and then returns the pathway, then creating a hyperlink to the sub-folder (this isn't part of the VBA code below) and looking at all excel files within, no matter the level of sub-folders within the main folder.
Here's the code:
Sub GetFolders()
Dim path As String
Dim folder As String
Dim row As Integer
path = "your directory here"
folder = Dir(path, vbDirectory)
row = 1
Do While folder <> ""
If (GetAttr(path & folder) And vbDirectory) = vbDirectory Then
Cells(row, 1) = path & folder
row = row + 1
End If
folder = Dir()
Loop
End Sub
This is great, but I know there has to be a better way. How can I manipulate this code to return COLUMN HEADERS of any excel files found A) within a folder or B) within a subfolder contained within a folder. I want these to be returned to an excel spreadsheet so that 100's of excel documents don't need to be opened, but rather just this one, and then we can identify any excel spreadsheets that need further investigation and ignore the rest.
You can query them with ADO (adjust the connection string as needed):
'Requires reference to Microsoft ActiveX Data Objects #.# Library
Private Function GetHeaders(filepath As String) As String()
Dim output() As String
Dim ado As New ADODB.Connection
output = Split(vbNullString)
With ado
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & filepath & "';" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;"";"
With .OpenSchema(adSchemaTables)
Dim table As String
Dim columns As ADODB.Recordset
Do While Not .EOF
table = .Fields("TABLE_NAME")
Set columns = ado.OpenSchema(adSchemaColumns, Array(Empty, Empty, table))
With columns
Do While Not .EOF
ReDim Preserve output(UBound(output) + 1)
output(UBound(output)) = table & .Fields("COLUMN_NAME")
.MoveNext
Loop
End With
.MoveNext
Loop
End With
End With
GetHeaders = output
End Function
Then call it like this for each file that you find:
Sub Example()
Dim headers() As String
Dim i As Long
headers = GetHeaders("C:\Foo\Bar.xlsx")
For i = LBound(headers) To UBound(headers)
Debug.Print headers(i)
Next i
End Sub
Note that this assumes you don't know the sheet names and need to get headers for all of them. The strings in the output array will be in the form of Sheet$Field, but that can be adjusted according to need.
Cell in col header is limited to 255 chars only due to limitation in ADODB.
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