How do I pass value in textbox on form to subroutine? - vba

I have a simple form with a few combo boxes, a textbox where the user enters the file name they want to save as (will be a spreadsheet), and a few buttons to run a few queries. When a button is pressed it opens the file dialog to select the path but the file name itself is hard coded in the subroutine. How do I take the value in the text box and pass it to the button event routine that runs the appropriate query and exports a spreadsheet? In the routine I called it fileName and the text box on the form is called FileName.
Option Compare Database
Option Explicit
Private Sub AllPaybacks_Click()
Dim getFolder As Object
Dim sLoc As String
Dim fileName As String
Set getFolder = Application.FileDialog(msoFileDialogFolderPicker)
With getFolder
.AllowMultiSelect = False
If .Show = True Then
sLoc = getFolder.SelectedItems(1) & "\"
End If
End With
DoCmd.OpenQuery "PaybackQ"
DoCmd.TransferSpreadsheet acExport, , "PaybackQ", sLoc & fileName & ".xlsx", True
End Sub

I'm a little uncertain what your exact question is.
If you want to populate the file name dialog then you can set the InitialFileName property of the getFolder object. So, inside the "with" block and before the "If" statement:
getFolder.InitialFileName = FileName.Value

Related

Access VB export certain query to designated filepath

So I have a query named "the query I wish to export", I want to be able to export the query to Excel when I click the button on my form.
I created this function in Module1 to call the dialog out and determine which file path I want to save my query result to.
Public Function ExportToExcel(strQuery As String)
On Error GoTo Err_Handler
Const MESSAGETEXT = "Overwrite existing file?"
Dim OpenDlg As New BrowseForFileClass
Dim strPath As String
OpenDlg.DialogTitle = "Enter or Select File"
strPath = OpenDlg.GetFileSpec
Set OpenDlg = Nothing
If strPath <> "" Then
If Dir(strPath) <> "" Then
If MsgBox(MESSAGETEXT, vbQuestion + vbYesNo, "Confirm") = vbNo Then
Exit Function
Else
Kill strPath
End If
End If
Else
Exit Function
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, strQuery, strPath
Exit_Here:
Exit Sub
Err_Handler:
MsgBox Err.Description
Resume Exit_Here
End Function
After complete this function, I call this function and wish to export my query to the filepath that I wish to select.
Private Sub Export1_Click()
Call Module1.ExportToExcel "the query I wish to export"
End Sub
It just keeps giving me "Syntax Error". I don't really understand because I specifically call the function, passing the query name as its argument, any ideas?
Since you're evaluating the function using the Call keyword (which isn't strictly required), the arguments will need to be enclosed in parentheses, i.e.:
Call Module1.ExportToExcel("the query I wish to export")
For the file selection/specification, I would suggest using the FileDialog object, which will require a reference to the Microsoft Office ##.0 Object Library.
To provide an example of how this may be implemented, below is a quick function to demonstrate how you might go about prompting the user to specify/select an Excel file:
Function GetExcelFile(msg As String) As String
Dim dia As FileDialog
Set dia = Application.FileDialog(msoFileDialogFilePicker)
With dia
.AllowMultiSelect = False
.Title = msg
.Filters.Clear
.Filters.Add "Excel Files", "*.xls; *.xlsx"
If .show Then
GetExcelFile = .SelectedItems.Item(1)
End If
End With
End Function
Call the above with the desired dialog title, e.g.:
GetExcelFile "Enter or Select File"
The above will return an empty string if the user presses Cancel when prompted.

Open a Word 2013 legacy Open dialog in a specific folder

I have a simple Word macro that shows the legacy Open dialog.
Sub LegacyOpen()
DoEvents
Dialogs(wdDialogFileOpen).Show
End Sub
I’m now trying to get it to open in a specific folder.
"C:\Users\Paul Schroeter\Documents\Microsoft Word Documents".
After about an hour I have not found an macro argument or example of how to get it to do what I want it to do.
If you wonder why I need to do this, it’s because every time I use “Search documents” in the legacy Open dialog, it resets the Open dialog path to "C:\Users\Paul Schroeter\Documents", which is driving me insane, because I then have to change it back to the folder where I actually keep my Word documents.
A number of the built-in Word dialog boxes have "dialog box arguments" corresponding to some of the controls/settings in the dialog box. A list can be found here. These are not part of the Intellisense and are late-bound into the object model. The developer needs to know they exist and how to look them up and use them.
One of these built-in arguments is to set/read the file full name from the File/Open dialog box. In VBA the arguments are usually used in a With block. Putting the argument before the Show or Display method executes the setting before the dialog box is shown to the user. If it's placed after the method, then it's used to read the user's choice.
Sub WordFileOpen()
Dim dlg As Word.Dialog
Dim sPath As String
Set dlg = Application.Dialogs(wdDialogFileOpen)
sPath = "C:\Users\Paul Schroeter\Documents\Microsoft Word Documents"
With dlg
.Name = sPath
.Show
End With
End Sub
If you consider something different than Dialogs collection you could use FileDialogs property. Here is working example:
Sub OtherWindowType()
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.AllowMultiSelect = False
.InitialFileName = "c:\" '...your path here
.Show
End With
'if you want to open the file...
If FD.SelectedItems.Count > 0 Then
Documents.Open FD.SelectedItems(1)
End If
End Sub

copy formatted text into access using vba

I need to save formatted text from Word in an Access Database.
So far I've managed to figure out how to store formatted text in an Access Field (Create a Memo Field in a Table and set the Text Format as Rich Text). Searching SO I have not yet come across a solution as to how to transport said text from word into Access.
I know that it is possible, because you can do it by simply copying and pasting the information if you are doing it manually.
My question, how can I copy formatted text from word into a field in a table using VBA?
Experimentally I created the following to test this. So far without success...
Sub GetComments()
'Imports Analyst Comments from Excel files als OLE Objects.
'---------------------------------
'Access Variables
Dim dbsFundDB As DAO.Database
Dim rsComments As DAO.Recordset
Set dbsFundDB = CurrentDb
Set rsComments = dbsFundDB.OpenRecordset("tblFunds")
'Word Variables
Dim doc As Word.Application
Dim dcmt As Word.Document
Dim sectn As Word.Section
Dim obCommentText As Object
Dim sAnalystText As String
'Open New Word File
Set doc = New Word.Application
doc.Visible = True
Set dcmt = doc.Documents.Open(sPathTemplate)
Set sectn = dcmt.Sections(1)
sectn.Range.Select
Selection.InsertFile FileName:="myfile.rtf", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
sAnalystText = sectn.Range.Tables(1).cell(1, 1).Range.FormattedText
rsComments.AddNew
rsComments![Long Comment Exec] = sAnalystText
rsComments.Update
sectn.Range.Select
dcmt.Close savechanges:=False
doc.Quit
End Sub
UPDATE
I tried implementing the answer from Matt Hall. While the text is indeed copied to the database, it does not yet keep the formatting:
Here is my implementation as a simple test:
Option Explicit
Public Const sPathTemplate As String = "W:\L\BDTP\Products\FundResearchTool\Advisory.docx"
Option Compare Database
Sub GetComments()
'Imports Comments from word and save in DB
'Test soubroutine
'---------------------------------
'Word Variables
Dim obCommentText As Variant
Dim strSQL As String
obCommentText = GetWordContent(sPathTemplate)
strSQL = "insert into [tblText]([TestField]) values('" & obCommentText & "')"
DoCmd.RunSQL strSQL
MsgBox "Import Successful", vbInformation Or vbOKOnly
End Sub
Private Function GetWordContent(strFile As String) As Variant
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents
Dim objDoc As Word.Document
Set objDoc = GetObject(strFile)
GetWordContent = CVar(objDoc.Sections(1).Range.Text)
objDoc.Close
End Function
Here's a method that heavily references this.
Before you start make sure you have these (or your Access version's equivalent) references ticked in VBA editor > Tools > References:
Microsoft Word 15.0 Object Library
Microsoft Office 15.0 Object Library
Assuming you've set up a form with a command button to trigger this MS-Word import, put the following function and subroutine somewhere in that form's VBA module:
1) File Picker Function:
This will allow you to select the MS-Word Document you want to using the old familiar file dialogue window you see throughout Windows. Ultimately, all it does is save the file path and name of the file you've picked for use in in the subroutine described in (2)...
Private Function FileToOpen() As String
' This function will essentially allow you to browse to MS-Word document
' and then store the path of that file for use in the GetWordContent function
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select Word document to import"
.Filters.Clear
.Filters.Add "Word files", "*.doc?"
If _
.Show = True _
Then
For Each varFile In .SelectedItems
FileToOpen = varFile
Next
Else
FileToOpen = ""
End If
End With
End Function
2) Get Formatted Text Contents of MS-Word Document Subroutine:
This subroutine will use the file path and name of the MS-Word Document selected in the File Picker function (above) to open the MS-Word document, select all the text, copy it to the clipboard, paste it to a text box on an open form in Access and then close MS-Word...
Private Sub GetWordContent(strFile As String)
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents and paste them in to WordDocData textbox on
' the currently open form in Access
' Create an MS-Word Object:
Dim objDoc As Object
Set objDoc = CreateObject("Word.Application")
' Open the file selected in FileToOpen() and copy the contents to clipboard:
With objDoc
.Documents.Open strFile
.Visible = True
.Activate
.Selection.WholeStory
.Selection.Copy
End With
' Set the focus to the WordDocData textbox on the Access Form and paste clipboard:
Me.WordDocData.SetFocus
DoCmd.RunCommand acCmdPaste
Me.WordDocDataSrc = strFile
' Save record on the form:
If _
Me.Dirty _
Then
Me.Dirty = False
End If
' A bit hacky this bit. When you close MS-Word after copying a lot of data,
' you might get a message asking you if you if you want to keep the last item
' you copied. This essentially overwrites the clipboard that currently has
' the whole document stored, to just the first 5 characters, which should allow
' MS-Word to be closed here without a pop-up message to deal with:
With objDoc
.Selection.HomeKey Unit:=wdLine
.Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
.Selection.Copy
.Documents.Close
.Quit
End With
Set objDoc = Nothing
End Sub
Your Command Button's On-click Event:
This subroutine should be run from your command button's on-click event. It essentially calls FileToOpen function and the GetWordContent subroutine in order for the user to select a MS-Word Document and then let the VBA copy and paste the formatted text from the MS-Word Document in to a rich text memo textbox on the open form in Access.
Note that this subroutine makes some assumptions, and refers to names of controls/tables/fields and whatnot that you might not have already setup. These assumptions are:
Your form's command button is called cmdGetWordData
Your Access database has a table called tblWordDump
Your form is bound to the table tblWordDump
tblWordDump has 2 memo text fields called WordDocDataSrc and WordDocData to store the imported file path/name and text contents respectively and both are added to your form
Private Sub cmdGetWordData_Click()
' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
' to retrieve the text contents of your chosen MS-Word Document.
' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.
' NOTE: this code assumes that your Access database has:
' - a table called tblWordDump
' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
' which will store the text and text formating of the MS-Word file imported
Dim strFile As String
Dim strWordContent As Variant
' Select file via File Dialogue
strFile = FileToOpen
' Conditionals when a file was or wasn't selected
If _
Len(strFile) > 0 _
Then
DoCmd.GoToRecord , , acNewRec
GetWordContent strFile
MsgBox "Import Successful", vbInformation Or vbOKOnly
Else
MsgBox "No File Selected", vbExclamation Or vbOKOnly
End If
End Sub
Here's an example Access file of this for you to poke about in.

Issue using FileDialog Application

I have a bit of code which I am trying to improve but having some issues.
The code is currently:
Sub TestListFilesInFolder()
'Workbooks.Add ' create a new workbook for the file list
' add headers
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker) ' Tried using a FileDialog Application but had no luck
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Old File Path:"
Range("B3").Formula = "File Type:"
Range("C3").Formula = "File Name:"
Range("D3").Formula = "New File Path:"
Range("A3:H3").Font.Bold = True
ListFilesInFolder "L:\Pictures\A B C\B526 GROUP", True
' ListFilesInFolder fd, True ' I tried replacing the above line with this line but get an error
' list all files included subfolders
End Sub
Line 5 and 6 is a part I have added in where I am trying to get a file dialog to open where the user can choose the folder for the code to work on.
Also The commented out line near the bottom starting ListFilesInFolder is the one I tried inserting to replace the line above it.
The start of the next bit of code is:
Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)
So it uses the folder and subfolders of that folder defined in the first sub.
Any help on this would be appreciated.
Regards,
Sam
You're passing fd as the first parameter to your ListFilesInFolder sub. This sub accepts a String as the first parameter, not a FileDialog.
Here's some sample code that, when executed, will open a file dialog and let the user select a folder. Once selected, it will print the path of the folder to B2. If no folder is selected (e.g. dialog is closed or canceled), B2 will contain the text No item selected.
I think you should create a new workbook and play around with this macro. Set a break point and walk through it, see what it's actually doing. Then you can alter it to make it work for your specific needs.
Public Sub SelectExportDestinationPath()
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then
sItem = "No item selected"
Else
sItem = .SelectedItems(1)
End If
End With
'if trailing slash is not found, add it
If Len(sItem) > 0 And InStr(Len(sItem), sItem, Application.PathSeparator, vbCompareText) = 0 Then
sItem = sItem & Application.PathSeparator
End If
Sheet1.Cells(2, 2).Value = sItem
Set fldr = Nothing
End Sub
make sure you have the appropriate reference picked:
Press Alt+F11 to open the VB Editor. In that window, choose menu items Tools -> References..., then look down the list for Microsoft Office XXX Object Library
It's 11.0 for Access 2003, 10.0 for Access 2002; 9.0 for Access 2000, 8.0 for Access 97 -- pick the right one.
Put a check mark in the box next to that reference, then close the dialog.
or, use the actual values, not the mso values
msoFileDialogOpen=1
msoFileDialogSaveAs=2
msoFileDialogFilePicker=3
msoFileDialogFolderPicker=4

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.