Is there a way to include recordset update in the same record as the rest of a form? - vba

I'm using a form to fill out a record in a table with multiple different fields. I am also using the form to create a folder that will hold copied files from another folder of the users choice. One of the fields is the filename of whichever files the user would like to copy. I am trying to add this information to a cell that is in the same record as the rest of the information I'm entering on the form. However, whenever I use the rs.AddNew method, it just adds the information I input into a cell in a new record, instead of the same one with the rest of the information I'm inputting on the form. I've tried using the rs.Edit method, but that only works if I go back to the previous record and input the information again. Is there a way to add the filename into the cell in the same record as the rest of the information I'm putting in?
Here is my script for this portion. The issue is in the last three lines of the final If statement.
'NOTE: To use this code, you must reference
'The Microsoft Office 14.0 (or current version)
'Object Library by clicking menu Tools>References
'Check the box for:
'Microsoft Office 14.0 Object Library in Access 2010
'Microsoft Office 15.0 Object Library in Access 2013
'Click OK
'http://analystcave.com/vba-application-filedialog-select-file/
'20171117
MsgBox "Select files you would like to copy to the " & DateTimeID.Value & " folder."
Dim fd As FileDialog, result As Integer
Dim db As DAO.database
Dim rs As DAO.Recordset
Dim stFileName As String
Const msoFileDialogOpen As Long = 3
Const msoFileDialogViewDetails As Long = 2
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set db = CurrentDb
Set rs = db.OpenRecordset("tblFieldLogAUTOID", dbOpenTable)
With fd
.AllowMultiSelect = True
'Optional FileDialog properties
.Title = "Select a file"
.InitialFileName = "C:\" 'We can start the file search at a certain point if data starts in the same directory across all computers
'Optional: Add filters
.Filters.Clear
.Filters.Add "Excel files", "*.xlsx" 'We can filter for the type of data files coming from the field to make it easier
.Filters.Add "All files", "*.*"
'Show the dialog. -1 means success!
If .Show = -1 Then
For Each it In .SelectedItems
Debug.Print it
stFileName = it
FileCopy stFileName, NewLocation & "\" & FileNameWithExt(stFileName)
rs.AddNew
rs!FileName = NewLocation & "\" & FileNameWithExt(stFileName)
rs.Update
Next it
End If
End With
End Sub
For an idea of what it's doing with the rs.AddNew method, here is an image with one record having the data I input from the form in one row, and another record with the filename in a cell on the next row.
enter image description here

Related

Save Picture in an MS Access 2016 Form Image Control to folder

This is my first time posting and before I get into my question I just want to say how much I appreciate all the time and effort everyone puts into solving these problems.
I'm working on setting up a simple project management system which uses both MS Access and Excel. Through various forms in Access a user can set up a new project with name, address, logo etc. For the logo a user can double click on an image control box and choose a jpeg from any folder they choose.
My problem is with saving the logo. When the user clicks on the Save button, I would like to save the picture into a specific folder, not the one the user choose from.
This code, which works as expected, gives me the file path of where the user chose the picture from and displays the picture.
Private Sub CompLogo_DblClick(Cancel As Integer)
Dim sFile As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Choose Logo"
.Filters.Clear
.Filters.Add "JPEG", "*.jpg"
If .Show = -1 Then
sFile = .SelectedItems(1)
End If
End With
If sFile <> "" Then
Me.CompLogo.Picture = sFile
End If
End Sub
I know I can save the path as text in an Access table...
Sub SaveNewProject()
Set rst = CurrentDb.OpenRecordset("ProjectsTbl", dbOpenTable)
rst.AddNew
rst!Logo = LogoFilePath
rst.Update
rst.Close
Set rst = Nothing
End Sub
... but I need the actual jpeg to be saved in the specific folder so it can be used later in the Excel side of the program.
Any help you can give is much appreciated.

Use VBA Code to Update External Datasource Links

I am looking to use VBA to update links for an external input file. I am a developer and the path for the linked input file I use will not be the same as the end user will need once it is placed in a production folder.
Is there a way to update the linked file location using VBA? I already have code that allows the user to specify the input file location and that information is saved in the [InputFolder] of the [Defaults] table. Is there a way to use VBA to update the Linked Table using the InputFolder field info?
The stored InputFolder data looks like this:
C:\Users\CXB028\OneDrive - Comerica\Projects\HR\Input Data
The new folder info would have a network drive location path defined that I do not have access to but the user would.
Here is the code I use to define and store the Input Folder location:
Private Sub btnInputFldr_Click()
On Error GoTo Err_Proc
Const msoFileDialogFolderPicker As Long = 4
Dim objfiledialog As Object
Dim otable As DAO.TableDef
Dim strPathFile As String, strFile As String, strpath As String
Dim strTable As String
Dim fldr As Object
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Choose Folder"
.Show
.InitialFileName = "" 'DFirst("InputFolder", "Defaults")
If .SelectedItems.Count = 0 Then
Exit Sub
Else
CurrentDb.Execute "UPDATE Defaults SET InputFolder='" & .SelectedItems(1) & "';"
End If
End With
Me.txtInputFldr.Requery
Exit Sub
Err_Proc:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Process Error"
End Sub
The linked table (an external excel spreadsheet) needs to be re-linked after the database is moved to the production location using VBA code when the new Input Folder is redefined.
I found some very simple and short code the worked great!! Please see below.
On Error Resume Next
'Set new file path location if the TABLE.FIELDNAME location exists
Set tbl = db.TableDefs("ENTER THE LINKED TABLE NAME HERE")
filePath = DLookup("ENTER YOUR LOOKUP TABLE FIELD NAME HERE", "ENTER YOUR LOOKUP TABLE NAME HERE") & "\ENTER YOUR EXCEL SPREADSHEET NAME HERE.XLSX"
tbl.Connect = "Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=" & filePath
tbl.RefreshLink
On Error GoTo 0
Hope someone else finds this as useful as I did!

Trying to link table between Access DBs using VBA. Getting ISAM not found error

I have a split database where both the front end and back end are accdb files. Because one of my tables uses the AppendOnly = Yes property, I cannot use the link table manager or the refreshlink property when I move the backend. The backend moves from time to time because my IT loves to reshuffle servers.
So my solution is to write a function which prompts for the backend location, deletes all the currently linked tables, and then loops through all the backend tables and links them to the frontend. On this last part I receive a run time error 3170 could not find suitable ISAM. I don't know why.
Code is below:
Public Function MoveDB()
'this function will replace the linked table manager. It will open a file select dialog box to allow the user to pick the new location of the DB backend.
'It will then break all the current links and then recreate them. We need to do this vice use the relink function because the cases table uses AutoAppend which stores old path data
' and breaks the relink function which is why linked table manager does not work.
' FileDialog Requires a reference to Microsoft Office 11.0 Object Library.
'variables to get the database path
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim DriveLetter As String
Dim NetworkPath As String
Dim DrivePath As String
Dim SubPath As String
'variables to link the database
Dim db As DAO.Database
Dim BEdb As DAO.Database
Dim oldtdf As DAO.TableDef
Dim tblName As String
Dim newtdf As DAO.TableDef
Dim BEtdf As DAO.TableDef
Set db = CurrentDb()
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
' Do not Allow user to make multiple selections in dialog box
.AllowMultiSelect = False
'set the default folder that is opened
.InitialFileName = CurrentProject.Path & "\BE"
' Set the title of the dialog box.
.Title = "Please select the Database Backend"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Access Databases", "*.accdb"
' Show the dialog box. If the .Show method returns True, the
' user picked a file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'We need to determine the full network path (including server name) to the DB backend. The reason is that different users may have the share drive mapped with different letters.
'If the backend is mapped using the drive letter of the user moving the DB then other users may not have a valid path. The full network path is universal
'Get the mapped drive letter from the path of the selected DB file
DriveLetter = Left$(Trim(fDialog.SelectedItems(1)), 2)
'Get the path of the selected DB file minus the drive letter
SubPath = Mid$(Trim(fDialog.SelectedItems(1)), 3)
'Get the full network path of the mapped drive letter
DrivePath = GETNETWORKPATH(DriveLetter)
'Combine the drive path and the sub path to get the full path to the selected DB file
NetworkPath = DrivePath & SubPath
'MsgBox (NetworkPath)
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
'Now we need to delete all the linked tables
For Each oldtdf In db.TableDefs
With oldtdf
If oldtdf.Attributes And dbAttachedODBC Or oldtdf.Attributes And dbAttachedTable Then
'this is a linked table
tblName = .Name
DoCmd.DeleteObject acTable, tblName
End If
End With
Next oldtdf
tblName = ""
'Now we link all the tables from the backend to the front end
Set BEdb = OpenDatabase(NetworkPath)
For Each BEtdf In BEdb.TableDefs
tblName = BEtdf.Name
If Left(tblName, 4) <> "~TMP" Then
Set newtdf = db.CreateTableDef(strTable)
newtdf.Connect = "Database = " & NetworkPath
newtdf.SourceTableName = tblName
newtdf.Name = tblName
db.TableDefs.Append newtdf
End If
Next BEtdf
End Function
The error occurs on the
db.TableDefs.Append newtdf
line. I'm looking to either make this code work, or a way around the known bug that prevents refreshing links when using the AppendOnly=Yes property.
Thanks in advance for any help.
I think you are just missing the semicolon on your string and remove extra spaces
newtdf.Connect = ";Database=" & NetworkPath
Alternatively, you can use DoCmd.TransferDatabase method and be sure to leave out the MSys tables as they have no direct application use between split files:
If Left(tblName, 4) <> "~TMP" And Left(tblName, 4) <> "MSys" Then
DoCmd.TransferDatabase acLink, "Microsoft Access", NetworkPath, _
acTable, tblName, tblName, False
End If
found this and worked for me
DAODataSet.SQL.Text := 'SELECT * FROM Country IN "" ";DATABASE=C:\SIMPLE.MDB;PWD=MyPassword"';
DAODataSet.Open;

Word bookmarks template using Access data

I have a Word template with bookmarks. These bookmarks pull data from an Access database application via VBA code.
On Error GoTo ErrHandler
Me.Recalc
If Me!txtCount = 0 Then
MsgBox "Please select a record to print.", vbOKOnly, "Error"
Else
Dim oWord As Object 'Word.Application
Dim doc As Object 'Word.Document
Set oWord = CreateObject("Word.Application")
Set doc = oWord.Documents.Open("C:\Request_Template.doc")
oWord.Visible = True
Dim oAccess As Object
Dim dbs As Database
Dim rst As Recordset
Dim strCriteria As String
With oWord.ActiveDocument
If .Bookmarks.Exists("DatePage1") = True Then
.Bookmarks("DatePage1").Select
If Not IsNull([Forms]![frmForRequest_Preview]!Date) Then
oWord.selection.Text = (CStr(Format([Forms]![frmForRequest_Preview]!Date, "mmm d, yyyy")))
Else
oWord.selection.Text = ""
End If
End With
End If
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
The question is how to open a copy of the template to allow the user to click on "Save" after reviewing the document? For now the original template is used and the user has to perform "Save As". That is not convenient.
"Template" in Word is a specific file type (.dot, .dotx or .dotm). As it stands, you don't have a Word "template", just a standard Word document (.doc).
Open this .doc in Word and save it as a "Document Template (.dot).
Now, change the line Documents.Open to Documents.Add, referencing the new .dot and changing the parameters to match those of the Add method.
This will automatically open a COPY of the template file, so there is never any danger of the user or your code overwriting the template.
Note, however, that "Save As" is still required since this is a new document, but it will come up automatically - the user won't have to think to use Save As. If you don't want the user to see Save As at all your code needs to perform Document.SaveAs and you need to know the file path and location to which it should be saved.

VBA MS Access 2007 hyperlink insert button

I have a button which inserts a hyperlink into a new record. The field's IsHyperlink property is set to "yes", so I get the hand, but clicking on the inserted path does not go anywhere. I believe the button is updating the record with the path of the file as "text to display" rather than "address."
Private Sub MSDS_btn_Click()
Dim fd As Office.FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Use a With...End With block to reference the FileDialog object.
With fd
'Set the initial path to the D:\Documents\ folder.
.InitialFileName = "D:\Documents\"
.Title = "Select MSDS"
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the action button...
If .Show = -1 Then
DoCmd.GoToRecord , "", acNewRec
Me![Link MSDS] = .SelectedItems(1)
**
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
I know that putting the following code in at the ** works in Excel, I am after something like it which will work in Access!
ActiveSheet.Hyperlinks.Add Anchor:=Cells(ActiveCell.row, Range("LinkCol").Column), Address:=.SelectedItems(1), TextToDisplay:="MSDS"
Try this if you want the file path as both the hyperlink address and display text.
Me![Link MSDS] = "#" & .SelectedItems(1) & "#"
If you want the address with only the file name (without the path) as the display text, try this:
Me![Link MSDS] = Dir(.SelectedItems(1)) & "#" & .SelectedItems(1) & "#"
See HyperlinkPart Method for more background information. You might even prefer to manipulate your hyperlink field data using HyperlinkPart.