How to create an access form which has two fields for importing two different excel files, and after selecting excel files press the button to run a query (already exist) and automatically export the query result in excel sheet. I was able to create the vba code (once played the import dialog will pop up waiting the user to enter the file path then pops up another time for the second file, another dialoge for exporting the result to excel. but the problem is how to do it using Forms in Microsoft Access.please give me suggestions or reference.
Agree with Boeckm, your question is a little lacking in detail :-)
If you are asking for the VBA code to fire the macro's you already have then simply create a button and add the following to the [on click] property
Private Sub Excel_button_Click(Cancel As Integer)
DoCmd.SetWarnings False ' Switch off "Are you sure" message
Dim stDocName As String
stDocName = "qry_Import file 1"
DoCmd.OpenQuery stDocName, acNormal, acEdit
stDocName = "qry_Import file 2"
DoCmd.OpenQuery stDocName, acNormal, acEdit
stDocName = "qry_Export file 3"
DoCmd.OpenQuery stDocName, acNormal, acEdit
DoCmd.SetWarnings True ' Switch on "Are you sure" message
End Sub
You can also build this in a single button using the wizzard (select misc, run query and select the first import query. Go back to the button and edit the [embedded macro] adding the others. You can also add the set warning = off to the series if required).
Related
Wow, my first stack question despite using the answers for years. Very exciting.
I'm fairly new to VBA and Excel and entirely new to Access, full disclosure. So Im trying to create a core database of lab reports, and I have a form for entering the information about a new report which adds info about the report to a master table of all reports, including assigning it a unique label. After entering the info, I then have a button which allows the user to select the Excel .csv file accompanying the report and imports it into the DB as a new table. It returns a success or error message. And it works! (And the code came from somewhere on here)
The problem is I'd like to then add a field to the new table that adds the label assigned to the new report to all records so it can be referenced by queries through the use of that label. I'd also like to add an index field to the new table if possible as it doesn't seem like importing the .csv as a table creates an index. I figure I'll make another sub that gets passed the new report name as a name for the new field (which will also be the value of the field through all records) and the table to append that to.
How do I pass this sub the newly imported table if I just imported it? I need this all to work from the button as it will mostly be my manager using this form/button to import new files, and they won't be able to just manually go into the tables as they are created and add fields (yes, I know that's the obvious solution, but trust me...this must be a button)
Heres the code I'm using (yes, I know lots of it could be done differently but it works!)
Public Function ImportDocument() As String
On Error GoTo ErrProc
Const msoFileDIalogFilePicker As Long = 3
Dim fd As Object
Set fd = Application.FileDialog(msoFileDIalogFilePicker)
With fd
.InitialFileName = "Data Folder"
.Title = "Enthalpy EDD Import"
With .Filters
.Clear
.Add "Excel documents", "*.xlsx; *.csv", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False 'Manual naming currently requires one file at a time be imported
'If aborted, the Function will return the default value of Aborted
If .Show = 0 Then GoTo Leave 'fb.show returns 0 if 'cancel' is pressed
End With
Dim selectedItem As Variant
Dim NewTableName As String
NewTableName = InputBox(Prompt:="Enter the Report Name", _
Title:="Report Name")
For Each selectedItem In fd.SelectedItems 'could later be adapted for multiple imports
DoCmd.TransferText acImportDelim, , NewTableName, selectedItem, True 'Imports csv file selected, true is 'has headers'
Next selectedItem
'Return Success
ImportDocument = "Success"
'Append report label and index
AppendReportLabelField(NewTableName, #What to put here as the table to append to?)
'error handling
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Function
ErrProc:
MsgBox Err.Description, vbCritical
ImportDocument = "Failure" 'Return Failure if error
Resume Leave
End Function
The AppendReportLabelField would get passed the name (and value) of the field and the name of the (newly imported) table. How do I pass it the table? NewTableName is just a string currently. If I can pass the new sub the table I'm sure the rest will be simple.
Thanks in advance for the help!
Consider storing all user input data in a single master table with all possible fields and use a temp, staging table (a replica of master) to migrate CSV table to this master table. During the staging, you can update the table with needed fields.
SQL (save as stored queries)
(parameterized update query)
PARAMETERS [ParamReportNameField] TEXT;
UPDATE temptable
SET ReportNameField = [ParamReportNameField]
(explicitly reference all columns)
INSERT INTO mastertable (Col1, Col2, Col3, ...)
SELECT Col1, Col2, Col3
FROM temptable
VBA
...
' PROCESS EACH CSV IN SUBSEQUENT SUBROUTINE
For Each selectedItem In fd.SelectedItems
Call upload_process(selectedItem, report_name)
Next selectedItem
Sub upload_process(csv_file, report_name)
' CLEAN OUT TEMP TABLE
CurrentDb.Execute "DELETE FROM myTempStagingTable"
' IMPORT CSV INTO TEMP TABLE
DoCmd.TransferText acImportDelim, , "myTempStagingTable", csv_file, True
' RUN UPDATES ON TEMP TABLE
With CurrentDb.QueryDefs("myParameterizedUpdateQuery")
.Parameters("ParamReportNameField").Value = report_name
.Execute dbFailOnError
End With
' RUNS APPEND QUERY (TEMP -> MASTER)
CurrentDb.Execute "myAppendQuery"
End Sub
If CSV uploads vary widely in data structure, then incorporate an Excel cleaning step to standardize all inputs. Alternatively, force users to use a standardized template. Staging can be used to validate uploads. Databases should not be a repository of many, dissimilar tables but part of a relational model in a pre-designed setup. Running open-ended processes like creating new tables by users on the fly can cause maintenance issues.
I'm creating a user form (with SAVE button that writes to Excel sheet and RETURN button that goes back to a splash page) and want to set/check a flag if there are unsaved changes on the form. I'm getting different functionality of the code depending on whether a breakpoint is set or not.
Here is the relevant portion of code:
Public saveFlag as Boolean
Private Sub UserForm_Initialize()
initializeCMAValues Me
initializeTeamValues Me, getRowNum("CMA", "Team", False)
' getRowNum is a function that returns the row to read from
' in this case, the row with name=CMA, type=Team, createRow=False
saveFlag = False
End Sub
Private Sub btn_Return_Click()
' Check for unsaved data
If saveFlag Then
If MsgBox("You have unsaved information on the form. Do you wish to save it?", vbYesNo, "Unsaved Data") = vbYes Then
btn_Save_Click
End If
End If
' Return to splash form
Unload Me
Form_Splash.Show
End Sub
If I enter the form and select RETURN, I get the msgbox prompt. If I set a breakpoint at the saveFlag = False line, enter form, select RETURN (invoking breakpoint), continue running, then it runs as I would expect (i.e., no msgbox).
Instead of a public saveFlag variable, I've tried writing the flag to a non-visible label on the form; I've also tried writing to a cell on the Excel sheet. Both gave the same results of this different behavior with and without the breakpoint.
I've also run the code with the initializeTeamValues line commented out and then the code runs fine. I've triple checked that this subroutine only fills values into the textboxes on the form, nothing else.
Some research turned up a vague answer related to OLE pushing values onto the stack. I then tried putting the "saveFlag = False" line at the beginning of the subroutine. Same results.
Ideas of why the varying behavior? Is there a better/alternate way to check for unsaved data?
In Excel 2007, when importing data via SQL/ODBC, it displays the message "Getting data" in the top-left cell of the import range. This occurs whether the query is run from the GUI or from VBA.
Can this message be suppressed..??? There seem to be no settings for it, either in the GUI or the VBA object properties of the WorkbookConnection, ODBCConnection, ListObject, or QueryTable.
I would like to create a customized "please wait" message with an animation, but the "Getting Data" message creates a visual conflict.
I tried the following, but it didn't suppress the message:
xl.ScreenUpdating = False
xl.DisplayAlerts = False
ExternalData_1: Getting Data...
Try disabling BackgroundQuery parameter:
With Selection.QueryTable
.BackgroundQuery = False
End With
Here is the problem from my original post:
I have a Word template (dotm) that has fields i would like filled in from a one-line/entry Excel file. I have a "Rough.txt", the contents of which i would like to insert into a specific place in this same mail-merge-generated document in addition to the information from the Excel file.
i would like to generate a DOC or DOCX from this scripting process that is saved in the same directory as the above-mentioned files. I would like this to be done by clicking run on a bat file or similar type of situation that does not involve me manually opening the file and clicking the buttons every time i want to do it. I would like it to be simpler than opening word manually and running the macro.
Plus, if i can put it in an executable/"runnable" file like a bat or something similar, then i can attach a shortcut to it and run it with Cortana voice commands. This is why i am going about it from this angle. This would be a GEM to have. Important here is that it runs when i tell it to, not scheduled at a certain time. I have done this with other bats with great success.
So i used a combination of what all the answers were to construct the following:
I have a bat file with a bunch of FART commands in it to correct many common grammar errors in a document; it's irrelevant and long, so i won't post it here. It's called FINISH-1.bat.
Then i have a second BAT file, FINISH-2.bat, which contains only the following:
"C:\Program Files\Microsoft Office 15\root\office15\winword.exe" "/mRunAllMacros" "C:\Transcription\Transcription\In Progress\NewKCJob\Transcript.docx"
So then I created about 20 find/replace Microsoft Word macros for styles which i will not post here since this was not relevant to the question.
I made two more macros in Word which are relevant to my issue. The following completes the mail merge for my Excel file, which is exported from Jotform.
Sub MailMergeCover()
'
' MailMergeCover Macro
'
'
ActiveDocument.MailMerge.OpenDataSource Name:= _
"C:\Transcription\Transcription\In Progress\JotformExport.xlsx", _
ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\Transcription\Transcription\In Progress\JotformExport.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet " _
, SQLStatement:="SELECT * FROM `Submissions$`", SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Windows("Transcript.docx [Compatibility Mode]").Activate
End Sub
And the following macro inserts my "Rough.Txt" document into the same transcript/Word document at the bookmark i inserted called "rough":
Sub InsertRough()
'
' InsertRough Macro
'
'
If ActiveDocument.Bookmarks.Exists("rough") = True Then
ActiveDocument.Bookmarks("rough").Select
Selection.InsertFile FileName:="C:\Transcription\Transcription\In Progress\NewKCJob\Rough.txt"
Else
MsgBox "Bookmark ""rough"" does not exist!"
End If
End Sub
The next step was to tie them all together in Word in a certain order so that my find/replace macros i mentioned earlier also apply to "Rough.txt":
Sub RunAllMacros()
Call InsertRough
Call Macro1
Call Macro2
Call Macro3
Call Macro4
Call Macro5
Call Macro6
Call Macro7
Call Macro8
Call Macro9
Call Macro10
Call Macro11
Call Macro12
Call Macro13
Call Macro14
Call Macro15
Call Macro16
Call Macro17
Call Macro18
Call Macro19
Call Macro20
Call MailMergeCover
End Sub
The second-to-last step was to make a third bat file, FINISH.bat, which Cortana will be using, to call the two bat files:
call "C:\Transcription\Transcription\In Progress\NewKCJob\FINISH-1.bat"
call "C:\Transcription\Transcription\In Progress\NewKCJob\FINISH-2.bat"
The last step was to create a shortcut to FINISH.bat in C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs called "Finish Job" for Cortana to index.
Now, i can say, "Hey, Cortana, open finish job," and it will do this for me all automatically.
i have just shaved 20 minutes to an hour off EVERY transcript i complete as i was doing many of these corrections manually. i would like to respect and follow the rules as much as i can, so if i am not giving enough detail or doing something abnormally, let me know so i can fix it. Again, thank you so much!! Really, i could not have crafted this without your help.
Based on the information you provide:
Create a template (*.dotm) for this. Double-clicking it in the Windows
Explorer/the Desktop will create a new document.
The text file: I'm assuming insert "as is" with no subsequent
processing, so just use the Insert/Text/Object/Text from file
command in the Word UI. Click the arrow next to the "Insert" button
in the dialog box and choose to insert with Link.
Use Word's built-in Mailings/Mail Merge tool to link to the Excel
data-source
Record a macro to execute the mail merge.
Create a macro named AutoNew in the template and copy the content of
the recorded macro into it. This macro will execute automatically
when a new document is created from the template.
Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.