ByRef argument type mismatch - Access VB - ms-access

I am receiving a ByRef argument type mismatch. The following code (varFile specificaly) is highlighted for the error:
Call InsertCMS_Reports_2ndSave(varFile)
Here is my form:
Option Compare Database
'Private Sub Command0_Click()
Private Sub cmdFileDialog_Click()
'Requires reference to Microsoft Office 12.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
'Clear listbox contents.
'Me.FileList.RowSource = ""
'Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Allow user to make multiple selections in dialog box.
.AllowMultiSelect = True
'Set the title of the dialog box.
.Title = "Please select one or more files"
.InitialFileName = "C:\Users\ABCDEF\Desktop\CCCEEe CMS Reports"
'Clear out the current filters, and add our own.
.Filters.Clear
'.Filters.Add "Access Databases", "*.MDB; *.ACCDB"
.Filters.Add "Access Projects", "*.txt"
'.Filters.Add "All Files", "*.*"
'Show the dialog box. If the .Show method returns True, the
'user picked at least one file. If the .Show method returns
'False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to the list box.
For Each varFile In .SelectedItems
' Me.FileList.AddItem varFile
Call InsertCMS_Reports_2ndSave(varFile)
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Module Code:
Function InsertCMS_Reports_2ndSave(FileName As String)
'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave"
DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _
"CMS_Reports_Import", "C:\Users\A088982\Desktop\January CMS reports for Centene\FileName"
CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = 'HLTH_COMPRPT_1701011028174_h0062.txt' WHERE FileName is NULL", dbFailOnError
End Function

The reason you're receiving this error is because you've dimensioned varFile as a variant, however your function is expecting a string. Try this instead:
Function InsertCMS_Reports_2ndSave(FileName)

Related

Get Access DB filename with FileOpenDialog then run query against table within it?

I want to browse/select a database file through an Access form and run a query on it based on the file path of the selected database file. I have tried like this:
SELECT *
FROM ExternalTableName IN '[Forms]![MyForm]![SelectedFilePath]'
WHERE Condition
...but that didn't work however this SQL did work:
SELECT *
FROM ExternalTableName IN 'C:\users\desktop\filename.mdb'
WHERE Condition
For browsing the file, I used this VBA snippet:
Private Sub cmd1()
Dim fd As FileDialog
Dim oFD As Variant
Dim fileName As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Add "Access Files", "*.mdb", 1
.Title = "Choose Text File"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
fileName = oFD
Next oFD
On Error GoTo 0
End With
'~~> Change this to the relevant TextBox
Me.TextFieldName = fileName
Set fd = Nothing
End Sub
Edit:
To query a table located in an MDB that the user selects from a File Open dialog, the simplest way (while avoiding additional References) is like this:
Option Explicit
Sub testQueryExternalTable()
'displays RecordCount from specified table, selected database
Const tableName = "tblLog"
Const defaultPath = "c:\users\" 'default path OR path+filename
Dim rs As Recordset, fName As String, sql as String
fName = getFileOpenDialog(defaultPath) 'get filename
If fName = "" Then MsgBox "You clicked cancel!": Exit Sub
sql = "select * from " & tableName & " in '" & fName & "'"
Set rs = CurrentDb.OpenRecordset( sql ) 'query the table
With rs
.MoveLast 'count records
MsgBox .RecordCount & " records found"
.Close 'close recordset
End With
Set rs = Nothing 'always clean up objects when finished
End Sub
Function getFileOpenDialog(defaultPath As String) As String
'returns filename selected from dialog ("" if user Cancels)
With Application.FileDialog(3)
.Title = "Please select a database to query" 'set caption
.InitialFileName = defaultPath 'default path OR path+filename
.AllowMultiSelect = False 'maximum one selection
.Filters.Clear 'set file filters for drop down
.Filters.Add "All Files", "*.*" '(in reverse order)
.Filters.Add "Access Databases", "*.mdb" '(last = default filter)
If .Show = True Then getFileOpenDialog = .SelectedItems(1) 'show dialog
End With
End Function
More Information:
MSDN : Application.FileDialog Property (Access)
MSDN : FileDialog.InitialFileName Property
MSDN : Accessing External Data with MS Access
MSDN : Database.OpenRecordset Method (DAO)
Original Answer:
It's easier (and more efficient) to use Access's built-in functionality rather than recreating it in VBA.
                                                              (Click to enlarge images)
   
The first option imports, and the seconds option emphasized textlinks without importing. Once the table is linked you can work with it in VBA or queries as if it's a local table.

MS Access Form button that allows user to browse/choose file, then imports file to a table

In my database, I can made a command button import a file using the following:
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", D:\Users\Denise_Griffith\Documents\Griffith\PRIME RECON FILES\jdaqawmslesfilesemailDLX_SHPREC_2017-04-26_03-33-47.csv, True, ""
But I would like to have the user choose the file to import, since the filename is different every day based on date and time it was created. I have found this site (http://access.mvps.org/access/api/api0001.htm) and was able to get the dialog to pop up to allow the user to navigate and select the file, but I do not know how to incorporate it so the file selected is imported using the specification I created, and into the appropriate table.
Please help!
You need to set a reference to Microsoft Office Object Library.
Public Sub ImportDocument()
On Error GoTo ErrProc
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Some Title"
With .Filters
.Clear
.Add "CSV documents", "*.csv", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False
If .Show = 0 Then GoTo Leave
End With
Dim selectedItem As Variant
For Each selectedItem In fd.SelectedItems
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
Next
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Sub
ErrProc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
Update after user's comments:
You must change the Sub to a Function and check the return value.
The simplest way is to return a Boolean, where FALSE indicates aborted and TRUE indicates success. However by doing so, you exclude the Error scenario as both Aborted and Error will return FALSE.
Therefore you can return a Long value e.g. 0, 1, 2 indicating Aborted, Success and Error respectively. In order to avoid the "magic numbers" though, I would create and return an Enum type as shown below:
Public Enum TaskImportEnum
Aborted = 0 'default
Success
Failure
End Enum
Public Function ImportDocument() As TaskImportEnum
On Error GoTo ErrProc
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Dialog Title"
With .Filters
.Clear
.Add "CSV documents", "*.csv", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False 'Change this to TRUE to enable multi-select
'If aborted, the Function will return the default value of Aborted
If .Show = 0 Then GoTo Leave
End With
Dim selectedItem As Variant
For Each selectedItem In fd.SelectedItems
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
Next selectedItem
'Return Success
ImportDocument = TaskImportEnum.Success
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Function
ErrProc:
MsgBox Err.Description, vbCritical
ImportDocument = TaskImportEnum.Failure 'Return Failure if error
Resume Leave
End Function
Lastly, you can call the Function like this:
Sub Import()
Dim status_ As TaskImportEnum
status_ = ImportDocument
Select Case status_
Case TaskImportEnum.Success:
MsgBox "Success!"
Case TaskImportEnum.Failure:
MsgBox "Failure..."
Case Else:
MsgBox "Aborted..."
End Select
End Sub
You can read more about the Enum type here: http://www.cpearson.com/excel/Enums.aspx

Adding Filename to a column with your textfile Import

I have built a form where a user can select one or more files and import them into a single table. When the user selects the file, or yet, multiple files, once the import is complete, I want the file name to be added on each row, of course, related to the correct file.
I am able to setup a query to manually add the filename, but how would I be able to do this in a more automated fashion. For example, if the user selects a file how can I code the SQL query to automatically detect the filename and add it? If the user selects more than one file, how can the query write the correct filename for each row?
Here is my form code:
Option Compare Database
'Private Sub Command0_Click()
Private Sub cmdFileDialog_Click()
'Requires reference to Microsoft Office 12.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
'Clear listbox contents.
'Me.FileList.RowSource = ""
'Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Allow user to make multiple selections in dialog box.
.AllowMultiSelect = True
'Set the title of the dialog box.
.Title = "Please select one or more files"
.InitialFileName = "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC"
'Clear out the current filters, and add our own.
.Filters.Clear
'.Filters.Add "Access Databases", "*.MDB; *.ACCDB"
.Filters.Add "Access Projects", "*.txt"
'.Filters.Add "All Files", "*.*"
'Show the dialog box. If the .Show method returns True, the
'user picked at least one file. If the .Show method returns
'False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to the list box.
For Each varFile In .SelectedItems
' Me.FileList.AddItem varFile
Call InsertCMS_Reports_2ndSave(varFile)
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Module Code:
Function InsertCMS_Reports_2ndSave(FileName As Variant)
'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave"
DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _
"CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName"
CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = 'HLTH_COMPRPT_1701011028174_h0062.txt' WHERE FileName is NULL", dbFailOnError
End Function
Provided the code you provided is already working, then this should work for you.
CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = '" & FileName & "' WHERE FileName is NULL", dbFailOnError
If you have issues, it's most likely a syntax issue with the sql string and quotation marks will be the most likely culprit. If you have problems, put a debug statement in your code so you can see what sql statement is getting generated. For instance:
Function InsertCMS_Reports_2ndSave(FileName As Variant)
Dim strSQL as String
'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave"
DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _
"CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName"
strSQL = "UPDATE CopyOfCOMPRPT_CE SET FileName = '" & FileName & "' WHERE FileName is NULL", dbFailOnError"
debug.print strSQL
CurrentDb.Execute strSQL, dbFailOnError
End Function

Access vba display local PDF file using web browser control

In ms access 2013, I have a user form (frm_viewer) containing a web browser control named wbContent.
I wrote the following code to populate and display a local PDF file but cannot seem to get it to function correctly.
I did manage to get it working by referencing the Control Source property of the control to a textbox on the same form (i.e. Control Source -> Base URL -> Expression Builder -> =[MyTextbox]) but I do not want to use this method, I prefer to populate it on the fly using variables.
Private Sub lblBrowse_Click()
'declare file dialog with late binding ->
Dim fDialog As Object, strPath As String
Set fDialog = Application.FileDialog(3) 'msoFilePicker
'set parameters ->
Me.wbContent.ControlSource = ""
'initializing the file dialog ->
With fDialog
.AllowMultiSelect = False
.Filters.Clear '
.title = "Please select a file..."
'display 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
strPath = .SelectedItems(1)
Debug.Print "SELECTED_FILE: " & strPath
'set source property to the string containing the full path ->
Me.wbContent.ControlSource = strPath
Me.wbContent.Requery
Else
End If
End With
End Sub
Could someone please take a look at my code and let me know how I can get it to function correctly?
Thanks!
Try this:
Me.wbContent.ControlSource = "='" & strPath & "'"
The control source needs to be a string like so: ='http://www.address.com'

How to use filedialogbox to save filepath in string, using Access VBA?

I have an Access file which I will be using for quality assurance of data.
I will be inputting data from three Excel files, each into its own Access table.
At present, I have three buttons and corresponding text boxes. I manually enter the file path and name into the text box, click the button and it completes the rest of my macro, importing the data.
I'd like to use the file picker dialog box to populate the textbox with the path.
This code and worked for me:
Private Sub Comando32_Click()
Dim f As Object
Dim strFile As String
Dim strFolder As String
Dim varItem As Variant
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For Each varItem In f.SelectedItems
strFile = Dir(varItem)
strFolder = Left(varItem, Len(varItem) - Len(strFile))
MsgBox "Folder: " & strFolder & vbCrLf & _
"File: " & strFile
Me.certidao.Value = varItem
Next
End If
Set f = Nothing
End Sub
Of course, it is possible to call the file Dialog API in VBA!
An example direct from Microsoft VBA documentation:
Private Sub cmdFileDialog_Click()
' Requires reference to Microsoft Office XY.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
' Clear listbox contents.
Me.FileList.RowSource = ""
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
' Allow user to make multiple selections in dialog box
.AllowMultiSelect = True
' Set the title of the dialog box.
.Title = "Please select one or more files"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Access Databases", "*.MDB"
.Filters.Add "Access Projects", "*.ADP"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to our list box.
For Each varFile In .SelectedItems
Me.FileList.AddItem varFile
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Please note you have to include a reference to Microsoft Office 11.0 Library
(in code window, select menu option Tools, Reference and select your library for the correct version of your Office Version)
Thanks for the response.
I did google it first and tried everything I came across. I also came across the very set of code pasted above. I Played around with it for a while and whatever I did returned errors. I decided to try the code in Excel instead of Access and it worked straight away. The only thing I could think was that the code wasn't applicable to access. Following all of that I asked the question here.
Private Sub cmdDialog_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Me.txtFileSelect.RowSource = ""
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select one or more files"
.Filters.Clear
.Filters.Add "Excel Files", "*.XLSX"
.Filters.Add "All Files", "*.*"
If .Show = True Then
For Each varFile In .SelectedItems
Me.txtFileSelect.AddItem varFile
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
With this code I get:
Compile error;
User-defined type not identified
Try this code, for single file:
MyFileURL = aBrowseForFile("C:\users\")
Public Function aBrowseForFile(aStartFolder As String) As String
' Needs a reference to Microsoft Office Object Library 15.0
On Error GoTo Err_txtBrowseForFile
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 = 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", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
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
Put this function in a module, as it is.
Do not put some other code inside, so you can call it in other projects and build your own tools set.
Call it as shown above in your form.
This code runs well and it is tested.
If you want to check this code, in the debug window type
debug.print aBrowseForFile("C:\users\")
and see what happens. If you have other run-time or compile errors, please post another question.
Hope this helps
Thanks for the response.
I solved the problem in the end, I hadn't selected the object database. I found the following code to work:
Private Sub cmdInput_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select a file"
.Filters.Clear
.Filters.Add "Excel Files", "*.XLSX"
.Filters.Add "All Files", "*.*"
If .Show = True Then
For Each varFile In .SelectedItems
DoCmd.TransferSpreadsheet acImport, 10, "InputData", varFile, True, ""
Beep
MsgBox "Import Complete!", vbExclamation, ""
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub