Access 2016 VBA code to import files with variable names - ms-access

I am trying to use Access VBA to automate the import (by the push of a button) of daily files that exist in a format like this:
Final_Data_ver20181101063035.xlsx
where the numeric piece translates as: yyyymmddhhmmss.
However, without knowing exactly what time the file was created, Access can't find it. I've been trying something like:
Dim datepiece as String
Dim file as String
datepiece = format(Date,"yyyymmdd")
file = "c:\Users\brian\Final_Data_ver" & datepiece & "*" & ".xlsx"
But I keep getting errors when I try this. It's looking for a file literally named:
Final_Data_ver20181102*.xlsx
Maybe I'm just not able to use wildcards in a statement like this. Any help would be appreciated.
Thanks!

This is an example of how you could find all files like Final_Data_ver20181102*.xlsx in Folder c:\:
Sub Test()
Const TEMPLATE As String = "c:\Final_Data_ver20181102*.xlsx"
Dim filename As String
filename = Dir(TEMPLATE)
Do
If filename = vbNullString Then Exit Do
'Instead of just printing the filename you can use it to import it like you did before.
Debug.Print filename
filename = Dir
Loop
End Sub

Related

Import CSV into a new table -MS Access

I am trying to import CSV files located in a folder into Access as new tables and I have been trying with a code
Public Const rootdir = "C:\Users\deb670s\Desktop\importcsv"
Sub import()
Dim nr As Integer
Dim file As AcBrowseToObjectType
file = Dir$(rootdir & "*.csv")
nr = 1
Do While file <> ""
DoCmd.TransferText acImportDelim, "ImportSpec", "NewTableName-" & nr, rootdir & file, True, , msoEncodingCentralEuropean
file = Dir$
nr = nr + 1
Loop
End Sub
But I get an error saying variable not defined at msoEncodingCentralEuropean Can someone tell me where am I going wrong?
The last parameter must be a CodePage value:
Code Page Identifiers
Hummmm... I think you should try it this way.
http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpAllWktsSepTbl
Just change the XLS to CSV.

Check to see if two Ms-Access reports match in VBA?

Are there any ways in VBA to check the contents in two access reports to see if they both match?
A less ideal way to do this is to export both reports as a PDF using
DoCmd.OutputTo acOutputReport, "rptMyReport", acFormatPDF, "C:\Reports\MyReport.pdf"
and then have a pdf compare tools such as WinMerge with the xdocdiff plugin analyze the difference. It's not a very streamlined process.
I'm trying to unit test each report by comparing the output of a newer version to an older version of the report to see if anything broke or changed.
This is going to come down to old-fashioned debugging techniques like inserting temporary subtotal fields and other points of comparison.
I'd like to answer my own question. A way to do this is to export your reports as html files using the DoCmd.OutputTo and then read them into a string variable. You can then compare string together from the newer file and older file.
Here is an example code:
Public Function fncCheckMatchingReports(strPathOne As String, strPathTwo As String)
Dim oFSO As Object, oFS1 As Object, oFS2 As Object
Dim sText1 As String, sText2 As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
'Set oFS1 = oFSO.OpenTextFile("C:\Users\Desktop\test.html")
'Set oFS2 = oFSO.OpenTextFile("C:\Users\Desktop\test2.html")
Set oFS1 = oFSO.OpenTextFile(strPathOne)
Set oFS2 = oFSO.OpenTextFile(strPathTwo)
sText1 = oFS1.ReadAll()
sText2 = oFS2.ReadAll()
If sText1 = sText2 Then
fncCheckMatchingReports = True
Else
fncCheckMatchingReports = False
End If
End Function

need to dynamically insert attachment to an access form from a local system and save the address into a table

Hey i am new to access database.
I am creating a form in which i need to attach a excel file from the local system. I tried to use the attachment control to attach the document. But i am not able to store it into a table. I need to use that excel document for my further processing. I need to get the path from which the data is selected from my local system.
I hard coded the path and i was able to do my operation but now i need to dynamically fetch the data from the location.
thanks in advance
My code for hard coding looks like this
Private Sub Command4_Click()
Dim dbs As DAO.Database
Set dbs = CurrentDb
If (ifTableExists("featuretable") = True) Then
dbs.Execute "Delete * from featuretable"
End If
Dim filepath As String
filepath = "C:\Users\jolly#iese.fhg.de\Desktop\featurevalues.xlsx"**
DoCmd.TransferSpreadsheet acImport, , "featuretable", filepath, True
fmfeaturesubform.Form.Requery
End Sub
"Attach" and "import" are completely different things. i guess you want to import the excel sheet.
one way would be use the Application.FileDialog:
http://msdn.microsoft.com/en-us/library/office/ff196794(v=office.15).aspx
another way would be search your current folder and import matching filenames:
Dim mBaseFolder As String
Dim mFname as string
mBaseFolder = "C:\test\" ' or application.CurrentProject.Path
mFname = Dir(mBaseFolder & "*.xls")
Do While fname <> ""
DoCmd.TransferSpreadsheet acImport, , "featuretable", mFname , True
mFname = dir()
Loop

How to copy the contents of an attached file from an MS Access DB into a VBA variable?

Background Information:
I am not very savvy with VBA, or Access for that matter, but I have a VBA script that creates a file (a KML to be specific, but this won't matter much for my question) on the users computer and writes to it using variables that link to records in the database. As such:
Dim MyDB As Database
Dim MyRS As Recordset
Dim QryOrTblDef As String
Dim TestFile As Integer
QryOrTblDef = "Table1"
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset(QryOrTblDef)
TestFile = FreeFile
Open "C:\Testing.txt"
Print #TestFile, "Generic Stuff"
Print #TestFile, MyRS.Fields(0)
etc.
My Situation:
I have a very large string(a text document with a large list of polygon vertex coordinates) that I want to add to a variable to be printed to another file (a KML file, noted in the above example). I was hoping to add this text file containing coordinates as an attachment datatype to the Access database and copy its contents into a variable to be used in the above script.
My Question:
Is there a way I can access and copy the data from an attached text file (attached as an attachment data type within a field of an MS Access database) into a variable so that I can use it in a VBA script?
What I have found:
I am having trouble finidng information on this topic I think mainly because I do not have the knowledge of what keywords to be searching for, but I was able to find someones code on a forum, "ozgrid", that seems to be close to what I want to do. Though it is just pulling from a text file on disk rather than one attached to the database.
Code from above mentioned forum that creates a function to access data in a text file:
Sub Test()
Dim strText As String
strText = GetFileContent("C:\temp\x.txt")
MsgBox strText
End Sub
Function GetFileContent(Name As String) As String
Dim intUnit As Integer
On Error Goto ErrGetFileContent
intUnit = FreeFile
Open Name For Input As intUnit
GetFileContent = Input(LOF(intUnit), intUnit)
ErrGetFileContent:
Close intUnit
Exit Function
End Function
Any help here is appreciated. Thanks.
I am a little puzzled as to why a memo data type does not suit if you are storing pure text, or even a table for organized text. That being said, one way is to output to disk and read into a string.
''Ref: Windows Script Host Object Model
Dim fs As New FileSystemObject
Dim ts As TextStream
Dim rs As DAO.Recordset, rsA As DAO.Recordset
Dim sFilePath As String
Dim sFileText As String
sFilePath = "z:\docs\"
Set rs = CurrentDb.OpenRecordset("maintable")
Set rsA = rs.Fields("aAttachment").Value
''File exists
If Not fs.FileExists(sFilePath & rsA.Fields("FileName").Value) Then
''It will save with the existing FileName, but you can assign a new name
rsA.Fields("FileData").SaveToFile sFilePath
End If
Set ts = fs.OpenTextFile(sFilePath _
& rsA.Fields("FileName").Value, ForReading)
sFileText = ts.ReadAll
See also: http://msdn.microsoft.com/en-us/library/office/ff835669.aspx

Reading and parsing large delimited text files in VB.net

I'm busy with an applicaton which reads space delimited log files ranging from 5mb to 1gb+ in size, then stores this information to a MySQL database for later use when printing reports based upon the information contained in the files. The methods I've tried / found work but are very slow.
Am I doing something wrong? or is there a better way to handle very large text files?
I've tried using textfieldparser as follows:
Using parser As New TextFieldParser("C:\logfiles\testfile.txt")
parser.TextFieldType = FieldType.Delimited
parser.CommentTokens = New String() {"#"}
parser.Delimiters = New String() {" "}
parser.HasFieldsEnclosedInQuotes = False
parser.TrimWhiteSpace = True
While Not parser.EndOfData
Dim input As String() = parser.ReadFields()
If input.Length = 10 Then
'add this to a datatable
End If
End While
End Using
This works but is very slow for the larger files.
I then tried using an OleDB connection to the text file as per the following function in conjunction with a schema.ini file I write to the directory beforehand:
Function GetSquidData(ByVal logfile_path As String) As System.Data.DataTable
Dim myData As New DataSet
Dim strFilePath As String = ""
If logfile_path.EndsWith("\") Then
strFilePath = logfile_path
Else
strFilePath = logfile_path & "\"
End If
Dim mySelectQry As String = "SELECT * FROM testfile.txt WHERE Client_IP <> """""
Dim myConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilePath & ";Extended Properties=""text;HDR=NO;""")
Dim dsCmd As New System.Data.OleDb.OleDbDataAdapter(mySelectQry, myConnection)
dsCmd.Fill(myData, "logdata")
If Not myConnection.State = ConnectionState.Closed Then
myConnection.Close()
End If
Return myData.Tables("logdata")
End Function
The schema.ini file:
[testfile.txt]
Format=Delimited( )
ColNameHeader=False
Col1=Timestamp text
Col2=Elapsed text
Col3=Client_IP text
Col4=Action_Code text
Col5=Size double
Col6=Method text
Col7=URI text
Col8=Ident text
Col9=Hierarchy_From text
Col10=Content text
Anyone have any ideas how to read these files faster?
-edit-
Corrected a typo in the code above
There are two potentially slow operations there:
File reading
Inserting lots of data into the db
Separate them and test which is taking the most time. I.e. write one test program that simply reads the file, and another test program that just inserts loads of records. See which one is slowest.
One problem could be that you are reading the whole file into memory?
Try reading it line by line with a Stream. Here is a code example copied from MSDN
Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) Then
Console.WriteLine(line)
End If
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
End Sub
End Class
From the top of my head id say try to impelement some kind of threading to spread the workload.