Add user input to Excel table upon upload to Access database - excel

I'm trying to combine user inputs with existing Excel file data so they will all be included in a single table when they are uploaded to the Access database.
Here is the way I have it laid out, but I'm open to changing it however need be.
I'm just completely stuck with what to do next. Upload Date is automatically filled in, but the rest of the parameters will vary based on the product and will have to be filled in manually. I also want it to be mandatory that every field is filled in, so have an error message saying "Enter all parameters" or something like that if they aren't, which wouldn't allow the upload to be completed.
The reason why this is necessary to do in Access and simply not Excel is because the Excel file is generated by AutoCad Electrical and is limited in what data it can include. I tried adding the columns in Excel and importing them and it worked, but my boss said we NEED the user input box to make things easier.
This is the code I have to import the Excel file and add it to the correct table (_MCL UPLOAD). Now I just want to be able to have the user inputs add to this table as extra columns:
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
'load spreadsheet
DoCmd.TransferSpreadsheet acImport, 8, "_MCL UPLOAD", selectFile(), True
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
Function selectFile()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
If .Show Then
selectFile = .SelectedItems(1)
Else
'stop execution if nothing selected
End
End If
End With
Set fd = Nothing
End Function

My final code looks like this:
'Import MCL Files Code
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
'load spreadsheet in .xls format
DoCmd.TransferSpreadsheet acImport, 8, "_MCL_UPLOAD", selectFile(), True
DoCmd.OpenQuery "UpdateMCL"
Call InsertInto_MASTER_UPLOAD
Call Delete_MCL_UPLOAD
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
'Function called in Import MCL Code above
Function selectFile()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
If .Show Then
selectFile = .SelectedItems(1)
Else
'stop execution if nothing selected
End
End If
End With
Set fd = Nothing
End Function
'Function Used to Delete MCL Uploaded file after it's moved to Master Table
Sub Delete_MCL_UPLOAD()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("default_cat.mdb")
' Delete employee records where title is Trainee.
dbs.Execute "DELETE * FROM " _
& "_MCL_UPLOAD "
dbs.Close
End Sub
'Function Appends _MCL UPLOAD into the _MASTER_UPLOAD table
Sub InsertInto_MASTER_UPLOAD()
Dim dbs As Database
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("default_cat.mdb")
' Select all records in the New Customers table
' and add them to the Customers table.
dbs.Execute " INSERT INTO _MASTER_UPLOAD " _
& "SELECT * " _
& "FROM [_MCL_UPLOAD];"
dbs.Close
End Sub
I basically created another table to dump all of the combined information into. Thanks for all of your help!

Related

Automation error on main code, but working on back-up code - VBA Excel

So i have 2 workbooks that contains the same code because I have to check the code with somebody else.
But the thing is, on the back-up workbook everything is working just fine, but on the main one, I have a "Run-time error -2147467259(80004005): automation error - unspecified error when it comes to this piece of code If wb1.BuiltinDocumentProperties("Last Save Time") > wb2.BuiltinDocumentProperties("Last Save Time") Then
Does anybody knows what could go wrong ? When I use the watch windows, i can see that "wb1" properties are not taken into accounts, but for the "wb2" it works
full sub :
Sub Fyle()
Set fd = Application.FileDialog(msoFileDialogFilePicker)
MsgBox ("Please choose 2 files to comparer.")
check = 0
While check <> 2
With fd
.InitialFileName = FPath
.AllowMultiSelect = True
.Show
End With
check = fd.SelectedItems.Count
If check <> 2 Then MsgBox ("please choose only 2 files")
Wend
Set wb1 = Workbooks.Open(fd.SelectedItems(1))
Set wb2 = Workbooks.Open(fd.SelectedItems(2))
If wb1.BuiltinDocumentProperties("Last Save Time") > wb2.BuiltinDocumentProperties("Last Save Time") Then
Call order(wb2, wb1)
MsgBox ("Vous allez comparer " & wb2.name & " avec " & wb1.name)
Else
Call order(wb1, wb2)
MsgBox ("Vous allez comparer " & wb1.name & " avec " & wb2.name)
End If
wb1.Close False
wb2.Close False
End Sub
i tried to copy and paste the whole code (many subs being called from different modules) from the back-up workbook to the main, but the error remains here.

Updating table in Access from Excel VBA

I have two tables in an Excel file which I need to import to Access and I have found a way that works perfectly for that, the problem is that it only works the first time (to import the table when this one does not exist in Access) but when I make changes to the Excel file and try this method again, it does not update the records and basically does nothing.
Both the table in Excel and in Access are called "Messungen" and "Grundinformation", respectively. This is the implemented code for the module called ExcelImport:
Public Sub ImportExcelSpreadsheet(fileName As String, tableName As String)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Messungen", _
fileName, True, "Messung!"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Grundinformation", _
fileName, True, "Grundinformation!"
Exit Sub
End Sub
I have made also the following objects. The first one to browse and select the file from a folder:
Private Sub btnBrowse_Click()
Dim diag As Office.FileDialog
Dim item As Variant
Set diag = Application.FileDialog(msoFileDialogFilePicker)
diag.AllowMultiSelect = False
diag.Title = "Bitte die Excel Datei 'DB_Access_Daten' wählen "
diag.Filters.Clear
diag.Filters.Add "Excel Spreadsheets", "*.xls, *.xlsx, *.xlsm"
If diag.Show Then
For Each item In diag.SelectedItems
Me.ExcelDatei = item
Next
End If
End Sub
And this one to import the table using a button:
Private Sub btnImportTabelle_Click()
Dim FSO As New FileSystemObject
If Nz(Me.ExcelDatei, "") = "" Then
MsgBox "Bitte eine Datei auswählen"
Exit Sub
End If
If FSO.FileExists(Nz(Me.ExcelDatei, "")) Then
ExcelImport.ImportExcelSpreadsheet Me.ExcelDatei, FSO.GetFileName(Me.ExcelDatei)
Else
MsgBox "File not found"
End If
End Sub
As mentioned before, this unfortunately is not working to update the values, just to import the table for the first time. I have thought of just linking the Database to the table in Excel but had some trouble with that since the excel file is in a shared network and my disk drive letter varies from the ones from my colleagues. I do not know then if maybe something is wrong with the code and how could I fix it.
Thank you for any help in advance!
You should link the spreadsheets. Then run an update/append query as shown here:
Update and Append Records with One Query

Access and VBA: Add date to all values of one column during import

I have problems with adding a date to column while importing an excel file. My set up is as follows:
I have an AccessDB where I want to import an Excel report on a daily basis. I have a form where I can browse for the report and import it by clicking a second button to a table called "tblImport". This works just fine.
I have now an empty column in the "tblImport" where I want to add the date of the report for every row that is not Null. The empty column is already defined as a date column. The date is at the end of the filename "YYYYMMDD.xlsx".
The perfect solution would be to get the date directly from the filename and add it to the column. But it would be also fine to add an input box or an field in the form where I have to add the date.
However, every solution I found did not work with my code.
I would be grateful for any suggestions.
Thanks in advance!
The code for the form is as follows:
Private Sub btnBrowse_Click()
Dim diag As Office.FileDialog
Dim item As Variant
Set diag = Application.FileDialog(msoFileDialogFilePicker)
diag.AllowMultiSelect = False
diag.Title = "Please select an Excel Spreadsheet"
diag.Filters.Clear
diag.Filters.Add "Excel Spreadsheets", "*.xls, *.xlsx"
If diag.Show Then
For Each item In diag.SelectedItems
Me.txtFileName = item
Next
End If
End Sub
Private Sub btnImportSpreadsheet_Click()
Dim FSO As New FileSystemObject
If Nz(Me.txtFileName, "") = "" Then
MsgBox "Please select a file!"
Exit Sub
End If
If FSO.FileExists(Me.txtFileName) Then
ExcelImport.ImportExcelSpreadsheet Me.txtFileName, FSO.GetFileName(Me.txtFileName)
Else
MsgBox "File not found!"
End If
End Sub
The import function looks as follows:
Public Sub ImportExcelSpreadsheet(fileName As String, tableName As String)
On Error GoTo BadFormat
DoCmd.RunSQL ("DELETE * FROM tblImport;")
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tblImport", fileName, True, "A1:F4"
MsgBox "Import successful!"
Exit Sub
BadFormat:
MsgBox "The file you tried to import was not an Excel spreadsheet."
End Sub
´´´
You need to write a function to get the date. This is based on the date being in the same place in the format mentioned. You can elaborate on this code, probably best to add some error checking in the date conversion function also. It's still early here so not fully tested :)
Public Sub ImportExcelSpreadsheet(fileName As String, tableName As String)
On Error GoTo BadFormat
docmd.runsql ("DELETE * FROM tblImport;")
docmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tblImport", fileName, True, "A1:F4"
' ***
docmd.runsql ("Update tblImport set DateImported='" & GetDateFromFileName(fileName) & "'")
' ***
MsgBox "Import successful!"
Exit Sub
BadFormat:
MsgBox "The file you tried to import was not an Excel spreadsheet."
End Sub
and
Function GetDateFromFileName(strInputFileName As String) As Date
Dim strDatePart As String
Dim intFinalDot As Integer
intFinalDot = InStrRev(strInputFileName, ".")
strDatePart = Mid(strInputFileName, intFinalDot - 8, 8)
GetDateFromFileName = DateSerial(Mid(strDatePart, 1, 4), Mid(strDatePart, 5, 2), Mid(strDatePart, 7, 2))
End Function

Running sub within sub (in a loop) causes textbox TabKeyBehavior to not work properly, ie = False

When dynamically creating textboxes/comboboxes on a userform, I create a combobox with information in another Excel workbook. (Not in the workbook I created the code/userform in. Nor can it be because it may change/get issued in the future & I don't want to have to move code into it).
After I create the combobox, I call another sub, Populate_Steel_List, to populate it. After everything has been generated, when tabbing through the textboxes/comboboxes actual Tab values are being placed in the textboxes/comboboxes, instead of moving on to the next textbox/combobox on the userform!
If I comment out calling for Populate_Steel_List, the userform's tabbing works fine. So I know calling it is causing the problem.
I tried adding a For-Next (For Each-Next as well) loop for each control, setting the .TabKeyBehavior = False. It didn't seem to do anything.
Here is my code:
Private Sub NumberMembers_Change()
' ....there is some other code in this sub, but has been tested,
' ie. commented out, till I found out
' where the offending code actually is
Dim TextBox8 As Object ' have also tried As Control; both run fine,
' but neither fix TabKeyBehavior on the userform
' Create Member Cross Section List Textboxes
Set TextBox8 = Controls.Add("Forms.ComboBox.1")
With TextBox8
.Name = "MemberSectionList" & i
.height = 17
.Width = 90
.Left = 494
.Top = 20 * i
.TabIndex = NextTabNumber + 3
End With
TextBox8Name(i) = TextBox8.Name
MembSectCurrBox = TextBox8.Name
Populate_Steel_List 'If I comment this out, the problem goes away,
' but that's not gonna work
End Sub
' ...and here's the code for Populate_Steel_List
Private Sub Populate_Steel_List()
Dim fd As Office.FileDialog
'Dim TextFile As Integer
' Check to see if log file has already been created
' Skip to using the path to find the excel document to have VBA read from it
If Len(FilePathToAISCShapesDatabase) > 0 Then GoTo Skip
If FilePathToAISCShapesDatabase = vbNullString Then
ChDir (Replace(ActiveWorkbook.FullName, ActiveWorkbook.Name, ""))
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the latest AISC shapes database file."
' Clear out the current filters, and add our own.
.Filters.Clear
.InitialFileName = "AISC Shapes Database v14.1.xlsm"
.Filters.Add "Excel", "*.xlsm, *.xlsx"
.Filters.Add "Excel 97–Excel 2003", "*.xls"
If .Show = True Then
FilePathToAISCShapesDatabase = .SelectedItems(1)
'Now I have the filepath to the AISC Shapes Database
Else
Exit Sub
End If
End With
' Create textfile in this location:
' Application.ThisWorkbook.Path & "AISCListLoc.txt"
'Open the text file
Open DirFile For Output As #1
'Write some lines of text
Print #1, FilePathToAISCShapesDatabase
'Save & Close Text File
Close #1
End If
Skip:
' Read from file that you have path to
Application.ScreenUpdating = False
Application.Workbooks.Open (FilePathToAISCShapesDatabase)
Dim rng As Range
Set rng = Sheets("Database v14.1").Range("C2:C" & Range("C" & Rows.Count).End(xlUp).row)
Me.Controls(MembSectCurrBox).List = rng.value
ActiveWorkbook.Close False
Application.ScreenUpdating = True
Set rng = Nothing
AppActivate ThisWorkbook.Application
Dim i ' Not sure if I really need to have this here or not;
' I also added it in the UserForm_Initialize(),
' but adding it doesn't seem to help
For i = 1 To Me.Controls.Count
If TypeName(Me.Controls(i - 1)) = "Textbox" Then
Me.Controls(i - 1).TabKeyBehavior = False
End If
Next
End Sub
TextBox8Name(i) is a private variant I used to keep track of how many comboboxes get generated (for limitations of an FEA program down the road).
FilePathToAISCShapesDatabase is a global string (in the module) so the user doesn't always have to point to the AISC shapes spreadsheet after the first time.
I tried not to select anything while in the other workbook, AISC Shapes Database v14.1.xlsm, but maybe I messed up?

excel and access integration

I have my front end in excel and backend as access. I send these files to client everyday.i do not want others to see the database. Is there a way to integrate access in excel such that if i transfer only excel file, access file also gets transferred automatically and others do not get to know about my database??
database should remain in access only.
You can't email or FTP an Access file invisibly, but you could move your data to a SQL Server (or other) database that is reachable from the internet.
However that poses several issues:
1) security
2) odbc DSN
3) availability of the odbc driver on the client machine
You can embed the Access database as an object into your Excel file (Insert->Object->Create from file , select Display as icon) and ask the user to extract and remove it. However, this is a bit cumbersome for both sides if you do it manually.
If you want to automate the process, use the following code:
Private Const cStrSheetName As String = "Sheet1"
Private Const cStrObjName As String = "EmbeddedFile"
Sub EmbedFile()
Dim strFile As String
Dim ws As Worksheet
Set ws = Sheets(cStrSheetName)
strFile = Application.GetOpenFilename("Any file (*.*), *.*", 1, _
"Please select a file to embed")
If strFile = "False" Then Exit Sub
On Error Resume Next
ws.Shapes(cStrObjName).Delete
On Error GoTo ErrorHandler
ws.OLEObjects.Add(Filename:=strFile, Link:=False, _
DisplayAsIcon:=True, IconFileName:="", _
IconIndex:=0, IconLabel:=strFile).Select
Selection.Name = cStrObjName
MsgBox "File succesfully embedded!"
Exit Sub
ErrorHandler:
MsgBox "Could not embed file. Error: " & _
Err.Number & " - " & Err.Description
End Sub
Sub ExtractEmbeddedFile()
Dim ws As Worksheet
Set ws = Sheets(cStrSheetName)
On Error Resume Next
ws.OLEObjects(cStrObjName).Copy
If Err.Number Then
MsgBox "No file embedded!"
Exit Sub
End If
On Error GoTo ErrorHandler
CreateObject("Shell.Application").Namespace(ActiveWorkbook.Path) _
.Self.InvokeVerb "Paste"
If MsgBox("File succesfully extracted to " & ActiveWorkbook.Path _
& vbCrLf & vbCrLf & "Do you want to remove the embedded " & _
"file from the this workbook to reduce its size?", vbYesNo) _
= vbYes Then
ws.Shapes(cStrObjName).Delete
End If
Exit Sub
ErrorHandler:
MsgBox "Error extracting file: " & _
Err.Number & " - " & Err.Description
End Sub
This will give you two macros (EmbedFile and ExtractEmbeddedFile) that you can assign to a button in your worksheet.
Please note that you need to modify "Sheet1" in the first line to the name of the worksheet you want to store the embedded file.

Resources