Access VB export certain query to designated filepath - vba

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.

Related

Open the file and save as another name

I want to create a new word file called "xxx_def_xxx" from selected word file called "xxx_docu_xxx".
So I select a file from dialog -> do something -> SaveAs with new file name.
It does work, but I'm getting "run time error 4160: Bad file name" if I select the file created from others, i.e., if the author is not me but another person.
I was struggling with this problem for couple of days but couldn't solve it.
Any help will be really thankful!
Private Sub CommandButton1_Click()
Dim fileOpen As FileDialog
Dim docuName As String, defName As String
Dim docu As Document
Set fileOpen = Application.FileDialog(FileDialogType:=msoFileDialogOpen)
With fileOpen
.Filters.Clear
.Filters.Add "Word Documents", "*.docx*"
.Title = "Select the docu"
.AllowMultiSelect = False
If .Show = -1 Then
docuName = .SelectedItems(1)
Else
Exit Sub
End If
End With
Set docu = Documents.Open(docuName)
'do something: remove or edit some texts in the file
defName = Replace(docu.Name, "docu", "def")
docu.SaveAs docu.Path & "\" & defName
docu.Saved = True
docu.Close
End Sub

MS Access: Upload multiple files from one button

I am trying to upload multiple files at once into an access database via the use of a button. However only one file will upload at a time.
When the button is clicked it calls a sub procedure. My code is below:
Private Sub btnImport_Click()
'Calls the procdure that imports raw files
Call Module1.ImportRawFiles
End Sub
Public Sub ImportRawFiles()
Dim oFileDiag As Office.FileDialog
Dim path As String: path = ""
Dim oFSO As New FileSystemObject
Dim FileSelected As Variant
Set oFileDiag = Application.FileDialog(msoFileDialogFilePicker) ''Picks file to import
oFileDiag.AllowMultiSelect = True ''Allows multiple files to be selected
oFileDiag.Title = "Please select the reports to upload"
oFileDiag.Filters.Clear
oFileDiag.Filters.Add "Excel Spreadsheets", "*.xlsx, *.xls" ''Only allows xlsx and xls file types to upload
If oFileDiag.Show Then
For Each FileSelected In oFileDiag.SelectedItems
Form_Homepage.txtFileName = FileSelected
Next
End If
If Nz(Form_Homepage.txtFileName, "") = "" Then
MsgBox "No files selected please select a file"
Exit Sub
End If
If oFileDiag.SelectedItems.Count > 0 Then path = oFileDiag.SelectedItems(1)
If Len(path) > 0 Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, oFSO.GetFileName(Form_Homepage.txtFileName), path, 1
MsgBox "The " & oFSO.GetFileName(Form_Homepage.txtFileName) & " file has been uploaded"
Else
MsgBox "File not found"
End If
Does anyone know why only one file is uploading?
You are looping through all selected files to assign Form_Homepage.txtFileName but then not doing anything else in that same loop:
If oFileDiag.Show Then
For Each FileSelected In oFileDiag.SelectedItems
Form_Homepage.txtFileName = FileSelected
Next
End If
So by end of the loop, the last selected file is assigned, ignoring all the others, then your later logic statements only perform on that one file.
One solution would be to move your action logic up to the same loop. So move your IF statements into the assignment loop, that way they operate on each iterative assignment of your variable.

Open Windows Explorer from Outlook to choose template [duplicate]

This question already has answers here:
Filepicker VBA to select file and store the file name not working
(2 answers)
Closed 3 years ago.
I am trying to write a macro that allows a user to select a .oft from a directory. I have been able to get a simple macro working that will open a specific .oft and modify the "from" field - this is what I have so far.
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate("c:\test\test.oft")
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
That works great, but there are numerous .oft files in the directory I am working with. I did find some articles that talk about setting up a toolbar with drop-downs and creating a macro for each .oft in the directory. I assume there has to be a better way than making a macro for each template.
I tried using this :
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate(Demo)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
Function Demo()
Call Shell("explorer.exe" & " " & "C:\test\", vbNormalFocus)
End Function
Windows Explorer will come up - but the macro throws an error and stops when you acknowledge the error.
Is there perhaps some way to have the user select the file through explorer.exe and save the path of the selected file to a variable, and then pipe that into .CreateItemFromTemplate?
After some digging around I got this to work. I am obviously a VBA noob so i take no credit for the code - I was just able to mash it together and get it to work. Maybe someone in the future will find it helpful.
Public Function aBrowseForFile(aStartFolder As String) As String
On Error GoTo Err_txtBrowseForFile
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Dim fDialog As Office.FileDialog
Dim varfile As Variant
Dim strPath As String
Dim strFilter As String, strFileName As String
Dim Main_Dir As String, DefFolder As String
Set fDialog = xlApp.Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.InitialView = msoFileDialogViewThumbnail
.AllowMultiSelect = False
.Title = "Please select one or more files"
.InitialFileName = aStartFolder
.InitialView = msoFileDialogViewThumbnail
.Filters.Clear
.Filters.Add "all files", "*.*"
If .Show = True Then
aBrowseForFile = .SelectedItems(1)
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
Exit_txtBrowseForFile:
Exit Function
Err_txtBrowseForFile:
MsgBox Err.Description, vbCritical, "MyApp"
Resume Exit_txtBrowseForFile
End Function
Sub EmailTemplateW10()
Dim MyFileURL As String
MyFileURL = aBrowseForFile("C:\users\")
Set msg = Application.CreateItemFromTemplate(MyFileURL)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub

MSAccess - Run-time error '438': Object doesn't support this property or method

I'm running into an error when I attempt to add filters to a FileDialog.
I've tried to troubleshoot this with multiple posts / articles but nothing seems to have solved it. The online documentation identifies using .Filters.Add but it doesn't seem that .Filters is an appropriate method. .Filter.Add is at least recognized but is still invalid. .Filter.Clear is also recognized but is invalid as well.
Code:
Private Sub Command93_Click()
Dim objFD As Object, strOut As String
Set objFD = Application.FileDialog(2)
With objFD
.Filter.Clear
.Filter.Add "Excel File", ".xls"
If objFD.show = -1 Then
strOut = objFD.selecteditems(1)
End If
End With
Set objFD = Nothing
Me.txtSaveFile = strOut
Me.Refresh
End Sub
Ok here is the answer. First, thanks to the above shots at solving for the issue as they did lead to me reviewing the documentation (again) and making another attempt. The first answer put me on to the issue as .Filters simply won't work with a msoFileSaveAs dialog. However, you can't type in a different file name on an Open dialog (either 1 or 3).
So the answer is to use msoFileSaveAs or (2) and use the .Initialfilename property to set the extension which, in this case, will show a list of excel files which can be selected, or selected and modified and then you can click on "Save"
Working code:
Private Sub Command93_Click()
Dim objFD As Object
Dim strOut As String
Set objFD = Application.FileDialog(2)
With objFD
'.Filters.Clear
'.Filters.Add "Excel File", "*.xls; *.xlsx", 1
.Initialfilename = "*.xlsx"
If .show = -1 Then
strOut = objFD.selecteditems(1)
End If
End With
Set objFD = Nothing
Me.txtSaveFile = strOut
Me.Refresh
End Sub
Thanks all!
You are using the the filters with the wrong dialog box. .Filters will work with msoFileDialogOpen which has a value of 1 or with msofiledialogfilepicker which has a value of 3. So try .Filters with Application.FileDialog(1) or Application.FileDialog(3) as shown below and it will work but it will not work with the msofiledialogsaveas which has a value of 2
The constants msoFileDialogOpen and msoFileDialogSaveAs are not supported in Microsoft Access. What it doesn't mean: is that the Application.FileDialog is NOT suported. What it means: is the constants are not supported. If you type ?msoFileDialogOpen in Immediate Window in MS Access, you will not see any value and hence we have to pass those values literally or declare them.
You have to use .Filters instead of .Filter
See this example
Option Explicit
Const msoFileDialogOpen As Integer = 1
Sub Sample()
Dim f As Object
Dim i As Long
Set f = Application.FileDialog(msoFileDialogOpen)
With f
.Filters.Clear
.Filters.Add "Excel File", "*.xls*"
.AllowMultiSelect = True
If .Show Then
For i = 1 To .SelectedItems.Count
MsgBox .SelectedItems(i)
Next
End If
End With
End Sub
Screenshot
EDIT:
If you want to use Filters in while saving then check out the link Display Open and Save As Dialog Boxes in Access with API Functions
Here you will see how to use filters in the using the .SaveFileDialog using the CommonDialogAPI

How do I call this subroutine from a button click on an Access form?

So, dumb question, but I can't figure it out. I have the following code that searches for a file path name and I believe adds the record to a table (untested). But, the problem is I am unable to Call this subroutine. I'd like to be able to click a button on a form and run. Does anyone know how I do this? thank you!
Public Function SelectFile() As String
Dim f As FileDialog
Set f = Application.FileDialog(msoFileDialogOpen)
With f
.AllowMultiSelect = False
.Title = "Please select file to attach"
If .Show = True Then
SelectFile = .SelectedItems(1)
Else
Exit Function
End If
End With
Set f = Nothing
End Function
Public Sub AddAttachment(ByRef rstCurrent As DAO.Recordset, ByVal strFieldName As String, ByVal strFilePath As String)
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
'Ask the user for the file
Dim filepath As String
filepath = SelectFile()
'Check that the user selected something
If Len(filepath) = 0 Then
Debug.Assert "No file selected!"
Exit Sub
End If
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Table1")
''''change this
'Add a new row and an attachment
rst.AddNew
AddAttachment rst, "Files", filepath
rst.Update
'Close the recordset
rst.Close
Set rst = Nothing
Set dbs = Nothing
End Sub
You would add an event procedure to the button in question:
In Form Design mode, click on the button
In the Properties Sheet, select the builder [...] button of the On Click event
You will go to the VBA editor. Enter code like:
Private Sub cmdAddAttachment_Click()
AddAttachment Nothing, "", ""
End Sub
That said, your AddAttachment routine has an apparent infinite loop. The line:
AddAttachment rst, "Files", filepath
Doesn't seem to actually fill any field values. In fact, variables rstCurrent, strFieldName and strFilePath are not used in the code. You probably will need to debug this routine before it will work.