Saving file with an incremental number using vba MS Access - ms-access

I am developing a database program and part of the program is the ability fr the user to attach files. These files are then copied to a specified folder and renamed to reflect the ID of the table. However, my question is that I can achieve this but when the user attaches second file for the same ID it throws error for file already exists.
So could anyone put me in the right direction on how to achieve this i.e. If file exits then save second file an incremental number soon.
some code to help to understand what i am trying to achieve:
Dim objFSO
Const OVER_WRITE_FILES = True
Set objFSO = Nothing
Dim FileLocation As String
Dim DestLocation As String
Dim fileName As String
Dim fileNameI As String
Dim iTemp As Integer
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileLocation = Me.lblTempLocation.Caption
DestLocation = "C:\Dev\"
fileName = [TestName].Value
'If the backup folder doesn't exist, create it.
If Not objFSO.FolderExists(DestLocation) Then
objFSO.CreateFolder (DestLocation)
End If
'Copy the file as long as the file can be found
If Not objFSO.FileExists(DestLocation & fileName & ".pdf") Then
objFSO.CopyFile FileLocation, DestLocation & fileName & ".pdf", OVER_WRITE_FILES
Else
objFSO.CopyFile FileLocation, DestLocation & fileNameI & ".pdf", OVER_WRITE_FILES
Do While (fileName) <> vbNullString
fileNameI = fileName & Format$(iTemp, "_00")
iTemp = iTemp + 1
Loop
End If
the above works fine first time but when the file exists and it goes through the loop it throughs a stack overflow error and stops the code.

Use ID key of first table as foreign key relationship to a second tables 'FKeyID' (one to many table). Create an 'AttachID' in the second table and set your VBA to rename the file based on the attachID allowing for multiple attaches per first table ID.
AttachID = second tables unique key
FKeyID = relation with ID from first table.

Related

Set cell value with VBA

I scan and save images with Wia using VBA in Microsoft Access.
The filepath to the saved image should be set as the value of the current cell.
I can't figure out how to do this but it seems like an easy task after learning how to use Wia.
Here is my current code that scans a document.
Function scanImage() As String
Dim imagePath As String
Dim folder As String
folder = "C:\Users\username\Pictures\scans\"
Dim tempName, obj
Set obj = CreateObject("Scripting.FileSystemObject")
tempName = obj.GetTempName
Dim filename
filename = Now
filename = Replace(filename, ".", "_")
filename = Replace(filename, " ", "_")
filename = Replace(filename, ":", "_")
imagePath = folder & filename & ".jpg"
Dim dev As Device
Dim wiaDialog As New WIA.CommonDialog
Dim wiaImage As WIA.ImageFile
Set dev = wiaDialog.ShowSelectDevice
Set wiaImage = wiaDialog.ShowAcquireImage
wiaImage.SaveFile (imagePath)
scanImage = imagePath
End Function
As comments have said - there's no cells in Access, and definitely no active cell.
You can add a record to a database using either of the methods below, but how do you plan on extracting that information again?
In Excel you just ask for the data in cell A1 for example, but in a database you generally ask for the data from a field or fields where another field on that same record is equal to some other values (either by supplying the 'other value' directly or by referencing other tables within the database).
So, for example, in your database you'd ask for the file paths of all files scanned on a certain date, or have some kind of description field to identify the file.
This would be written something like:
SELECT FilePath FROM Table2 WHERE DescriptionField = 'MyPhoto'
Anyway, the answer to get that single text string (imagepath) into a new record in a table is:
Sub InsertValueToTable()
Dim imagepath As String
imagepath = "<file path>"
'NB: The table name is 'Table2', the field (column) within the table is called 'FilePath'.
'One way to do it:
'DoCmd.RunSQL "INSERT INTO Table2(FilePath) VALUES ('" & imagepath & "')"
'Another way to do it:
Dim rst As dao.Recordset
Set rst = CurrentDb.OpenRecordset("Table2")
With rst
.AddNew
rst!FilePath = imagepath
.Update
.Close
End With
Set rst = Nothing
End Sub
Note - if you use a Text field in the database you'll be limited to 255 characters.

Attach file in MS Access using the path in the same record

I have some experience in MS Access, but can't seem to find vba that attaches the file to the record. I only have about 2,000 records (no more since it's a data entry project) so MS Access db size won't be an issue. Each record has the full path in a "path" field, but I can't figure out how to use vba to attach the file in a new "attachment" field.
Everything I've seen so far is about the user attaching a file or creating a path - not actually using the vba to attach the file (given that I already have the path).
Any help would be much appreciated!
You need to use the .LoadFromFile method of an Access DAO.Field2 object. For example, given a table named [tblTest]
ID - AutoNumber, Primary Key
MyFilePath - Text(255)
MyFileAttach - Attachment
containing
ID MyFilePath MyFileAttach
-- ------------------------------ ------------
1 C:\Users\Gord\Pictures\r.bmp #(0)
2 C:\Users\Gord\Pictures\g.bmp #(0)
3 C:\Users\Gord\Pictures\b.bmp #(0)
the following code will insert the specified file into the [MyFileAttach] field for each record
Dim cdb As DAO.Database, rstMain As DAO.Recordset, rstAttach As DAO.Recordset2, _
fldAttach As DAO.Field2
Set cdb = CurrentDb
Set rstMain = cdb.OpenRecordset("SELECT MyFilePath, MyFileAttach FROM tblTest", dbOpenDynaset)
Do Until rstMain.EOF
rstMain.Edit
Set rstAttach = rstMain("MyFileAttach").Value
rstAttach.AddNew
Set fldAttach = rstAttach.Fields("FileData")
fldAttach.LoadFromFile rstMain("MyFilePath").Value
rstAttach.Update
rstAttach.Close
Set rstAttach = Nothing
rstMain.Update
rstMain.MoveNext
Loop
rstMain.Close
Set rstMain = Nothing
Set cdb = Nothing

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

Import Unknown Field Order From Text

I've been assigned the task of importing about 180 csv files into an access 2007 database. These files have been put together over the years and will be put into 1 of 3 folders. I have not set up any data checks or restrictions to these tables (such as primary keys, validation rules, or relationships). That will be done once the data has been imported. The data contained in these files are from a survey which has changed over the years. This change has caused the fields to change. The order of them has changed or sometimes a field is there and sometimes it is not. I do have a list of all the fields possible though and what table each csv file should be imported to, and know that all these fields can be text.
Here is my problem: Not knowing what the order of the columns or if a column will exist, is it possible to run a function to import these text files into their relative tables by mapping each column in the text file to it's associated column in the access table?
Each text file has headers which is useful to see shat they actually are, but there is no text qualifier which can be very annoying when dealing with id codes consisting entirely of numbers. Below is what I've tried so far. It gets the file location from a function elsewhere, adds each filename in that location to a collection, then for each file in that collection it tries to import it into it's relative field.
'Get file names from the folder and store them in a collection
temp = Dir(location & "\*.*")
Do While temp <> ""
fileNames.Add temp
temp = Dir
Loop
'Go through each file in the collection and preccess it as needed
For Each temp2 In fileNames
If (temp2 Like "trip*") Then 'Import trip files
'Gets the data from a query 'DoCmd.RunSQL "SELECT * FROM [Text;FMT=Delimited;HDR=YES;IMEX=2;CharacterSet=437;DATABASE=" & location & "].[" & temp2 & "] As csv;"
DoCmd.TransferText acImportDelim, "Trips_Import", "tbl_Trips", location & "\" & temp2, -1
End If
If (temp2 Like "catch*") Then 'Import catch files
DoCmd.TransferText acImportDelim, "Catch_Import", "tbl_Catch", location & "\" & temp2, -1
End If
If (temp2 Like "size*") Then 'Import size files
DoCmd.TransferText acImportDelim, "Size_Import", "tbl_Size", location & "\" & temp2, -1
End If
Next temp2
You can create a SELECT * query for each CSV file and open the query as a recordset. Open another recordset for the destination table.
Then for each row in the CSV recordset, add a row to the destination recordset, loop through the CSV Fields collection, and add each CSV field value to the destination field with the same name.
This approach is independent of the order in which the fields appear in the CSV file. It also doesn't matter if the CSV file includes only a subset of the fields present in the destination table. As long as each CSV field also exists in the table, it should work (assuming compatible data types, the value satisfies validation rules/constraints, etc.).
Dim db As DAO.Database
Dim fld As DAO.Field
Dim rsDest As DAO.Recordset
Dim rsSrc As DAO.Recordset
Dim strSelect As String
Dim strTableName As String
Set db = CurrentDb
'Go through each file in the collection and preccess it as needed
For Each temp2 In fileNames
Select Case Left(temp2, 4)
Case "trip"
strTableName = "tbl_Trips"
Case "catc"
strTableName = "tbl_Catch"
Case "size"
strTableName = "tbl_Size"
Case Else
' what should happen here?
' this will trigger an error at OpenRecordset(strTableName) ...
strTableName = vbNullString
' figure out a better alternative
End Select
strSelect = "SELECT csv.* FROM " & _
"[Text;FMT=Delimited;HDR=YES;IMEX=2;CharacterSet=437;DATABASE=" & _
Location & "].[" & temp2 & "] As csv;"
Debug.Print strSelect
Set rsSrc = db.OpenRecordset(strSelect, dbOpenSnapshot)
Set rsDest = db.OpenRecordset(strTableName, dbOpenTable, dbAppendOnly)
With rsSrc
Do While Not .EOF
rsDest.AddNew
For Each fld In .Fields
rsDest.Fields(fld.Name).value = fld.value
Next
rsDest.Update
.MoveNext
Loop
.Close
End With
rsDest.Close
Next temp2
Note: This is a RBAR (row by agonizing row) approach, so the performance will be less than stellar. However, I presumed you will do this only once, so the performance hit will not be a deal-breaker. If you need a faster set-based approach instead, you can build and execute an "append query" for each CSV file. To do that, you would first need to get the CSV field names, and then build the appropriate INSERT INTO statement.

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