I am trying to have the file dialog box pop up so the user can select a file path to export a file in VBA but for some reason it throws this error on the following line of code.
Error: Method 'FileDialog' of object '_Application' failed
Code: longResult = Application.FileDialog(msoFileDialogFolderPicker).Show
All Code:
If choice = 6 Then
Dim intResult As Long
Dim strPath As String
'the dialog is displayed to the user
longResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
'dispaly message box
Call MsgBox(Application.FileDialog(msoFileDialogFolderPicker _
).SelectedItems(1), vbInformation, "Selected Folder")
End If
Else
End
End If
I am really unsure how to fix this issue. I checked my syntax and everything.
I know that this is a bit of an old question at this point, but since it doesn't actually have the answer, and I needed one today, I'm going to chime in with what I found just in case anyone else needs the answer too.
To fix this you need to add a reference to "Microsoft Office [yourversion] Object Library" in Visual Basic Editor >> Tools >> References...
The dialog in question should look like this:
Was trying to do the same thing myself and found this question. I realize that it is over a year old.
Try using the actual number (4) instead of msoFileDialogFolderPicker, that worked for me. I think something needs to be installed for the msoFileDialog constants to be initialized, when I tried printing any of the constants defined in the help file in the immediate window nothing was printed.
Also, why does your code have one variable longResult and one variable intResult?
Almost nothing is an integer in VB6 as integer is a VB4 16 bit type. Win32 Integers are called Long in VB6/VBA.
This was to make porting 16 bit code to 32 bit easy.
Check out http://msdn.microsoft.com/en-us/library/office/ff865217%28v=office.15%29.aspx for more information on proper syntax with FileDialogue.Show method. It appears you need a Set in front of your variable.
If you are after some cool UI, you can checkout my Github for sample database using .NET wrapper dll. Which allows you to simply call a function and to open filedialog with file-drag-and-drop function
Dim FilePaths As String
FilePaths = gDll.DLL.ShowDialogForFile("No multiple files allowed", False)
'Will return a JSONArray string.
'Multiple files can be opend by setting AllowMulti:=true
here what it looks like;
Related
MS Access (2007 - 2016) in Office 365
I'm trying/failing to capture a value passed into Access from the command line using the Command() function in a Macro. THis is the macro that I created with the wizard...
If Command()="Update_Burndown_Metrics" Then
RunSQL
SQL Statement insert .... blah, blah
End If
No error when I save the macro, but when I run...
The expression you entered has a function name that Microsoft Access can't find
If I replace the...
If Command()="Update_Burndown_Metrics"
with
If 1=1
It runs fine. IOW, it's not the SQL. It's the "Command() function that it can't find.
I got the idea to use Command() from Opening Microsoft Access with parameters . Doesn't seem to work for me. But that coding approach is also confirmed here... http://www.utteraccess.com/wiki/Command-Line_Switches . So I think it's something else.
Eventually, I would like to pass the Update_Burndown_Metrics arg using /cmd on the command line.
Why can't it find Command() as a valid function ? Is it a scoping thing? Do I have to give Command() context somehow, maybe with some sort of prefix ?
I can't seem to reproduce the issue that you are describing, though, I am using an earlier version of MS Access, and so there may be some differences in the behaviour of this function.
The Command function should be globally accessible, even outside of VBA (it can be referenced by the ControlSource property of a text box, for example), and so this isn't an issue of scope.
I do observe from the Office 365 documentation, that the Command function is being invoked without the use of parentheses in the sample VBA Sub provided; therefore it may be worth you trying your code without including such parentheses, e.g.:
If Command = "Update_Burndown_Metrics" Then
MsgBox "Test succeeded."
Else
MsgBox "Test failed."
End If
The workaround I created is to create a function in vba that gets and returns the command...
Public Function GetCommand() As String
GetCommand = Command()
End Function
Then...
If GetCommand() = "Update_Burndown_Metrics" Then ...
I have a small bit of code for a much larger MS Access database that likes to behave erratically. I can't say for sure, but it seems to change when I compile or recompile the database. Here's the code:
Private Sub FindCtls()
Dim DatType as String
Dim thisCTL as Control
DatType = Right(ActiveControl.Name, Len(ActiveControl.Name)-4)
For Each thisCTL In Me.Controls
If InStr(1, thisCTL.Name, DatType, 2) > 0 Then
Select Case Left(ThisCtl.Name,4)
Case "Sel_"
Set TgtCtls(0) = thisCTL
' A buncha other Cases
End Select
End If
Next thisCTL
End Sub
The problem is, when I step through the code, for some reason thisCTL is being passed as the value of the control, not the control itself. I've looked everywhere for this answer, that brought me to using the "Set" command instead of just putting TgtCtls(0) = thisCTL. That worked until I decompiled the DB and recompiled it. Made one change (changed the name of the first variable), compiled it again, and it worked. As I got into work today, someone told me that it was no longer working. Any ideas would be greatly appreciated.
Edit: I forgot to mention that TgtCtls is a form-wide array that was Dim'd at the top as such:
Option Compare Database
Dim TgtCtls(2) as Control
In a data validation form, I have a subroutine checking previously-entered data on a LostFocus event by ensuring that the release time (TimeReleased in table; Me.txtTimeReleased on form) is after the capture time (ObservationTime in table; Me.txtObservationTime on form). I'm using LostFocus rather than BeforeUpdate because the data were bulk-imported into the db and are now being error-checked.
My users keep getting a compile error (Compile Error: method or data member not found) upon tabbing out of the field this sub is attached to but I cannot reproduce the problem locally. The error occurs on this line:
If (Me.txtTimeReleased) <= (Me.ObservationTime) Then
and the part highlighted is '.txtTimeReleased'
Full code block:
Private Sub txtTimeReleased_LostFocus()
Dim badData As Variant
Dim resp As Variant
'Also check that time released is after time captured
If Not IsNull(Me.txtObservationTime) And Not IsNull(Me.txtTimeReleased) Then
If (Me.txtTimeReleased) <= (Me.ObservationTime) Then
resp = MsgBox("Release time must be after capture time." & vbCrLf & "Please double check this field's value: is it correct?", _
vbYesNo + vbExclamation + vbDefaultButton2, "Release Time Before Capture Time")
If resp <> vbYes Then badData = True
End If
End If
If badData = True Then
Me.cmbTaxonId.SetFocus 'set focus away so can set focus back
With Me.txtTimeReleased
.SetFocus
.SelStart = 0
.SelLength = 10
End With
End If
End Sub
Other things to note:
Both the table field and form control are formatted as 'Short Time' (24-hour time)
There is an input mask on that form control for 24-hour time; I use input masks very rarely and thus aren't familiar with them--perhaps the input mask could be causing the problem?
There are similar LostFocus subs on most of the other controls which do not produce this (or any other) error
Things I've tried:
Checking spelling
Fully decompling and recompiling the code: starting with shift, compact and repair with shift, open with /decompile flag while holding shift, compact and repair with shift, re-open with shift, and finally compile (without error)
Replacing the form in their database with one that works fine for me on the same data
Google
Things that seem odd to me:
I can't reproduce the error locally.
The error is triggering on the second instance of
Me.txtTimeReleased rather than the first: it has already passed a Not
IsNull(Me.txtTimeReleased) check.
The fact that it's a compile error: could that be masking something else?
Thanks for your time, and please let me know if there's any additional information that would be useful. Any thoughts are most welcome!
You checked for Null txtObservationTime and txtTimeReleased, but compare then txtTimeReleased and ObservationTime. Maybe solution is:
If Not IsNull(Me.txtObservationTime) And Not IsNull(Me.txtTimeReleased) Then
If (Me.txtTimeReleased) <= (Me.txtObservationTime) Then
Opening the .mdb with the /decompile flag is one of the first things I would have suggested, but you said you already tried that.
Here's another undocumented trick to deal with "hidden" compile problems that get baked in by VBA behind the scenes:
First, make a backup copy of your .mdb just to be safe (this is, after all, an undocumented technique).
Then, save your form to a text file using SaveAsText:
SaveAsText acForm, "MyFormName", "C:\MyFormName.txt"
Finally, re-load your form using the equally undocumented LoadFromText:
LoadFromText acForm, "MyFormName", "C:\MyFormName.txt"
Compile.
Compact.
Repair.
Hope for the best.
Good luck.
I suggest you use variables:
intThat = Me.txtTimeReleased
If intThis <= intThat Then
Try using ! instead of a dot:
intThat = Me!txtTimeReleased
If intThis <= intThat Then
And now, the answer that worked for me last week:
Comment out the offending line.
Run a compile that is successful.
Restore the offending line.
The compile may work now. Don't ask me why.
I would like Access to "automatically" play a song whenever a combo box is updated. I want that song to change depending on the contents of the combo box. Unfortunately the below code returns:
Constant expression required
Here's the code I'm working with:
Private Sub cboCustomerID_AfterUpdate()
txtSongFile = Me.cboCustomerID.Column(2)
Me.Refresh
Const conMEDIA_FILE_TO_OPEN As String = Me.txtSongFile
Me![WindowsMediaPlayer1].openPlayer (conMEDIA_FILE_TO_OPEN)
End Sub
Any help would be greatly appreciated!! Thank you.
The error you mentioned is a compile error, not a run time error. It is caused by this line:
Const conMEDIA_FILE_TO_OPEN As String = Me.txtSongFile
The reason is that the VBA rule for what you can use on the right side of the = sign is quite restrictive. This is what Access' online help says:
"Literal, other constant, or any combination that includes all arithmetic or logical operators except Is."
But you should be able to use a variable instead:
Dim strMEDIA_FILE_TO_OPEN As String
strMEDIA_FILE_TO_OPEN = Me.txtSongFile
I want to register a function kind of CalculateHours(work_hour, rest_hour) to Excel VBA, in an Addin like Works.xla
I tried using Application.MacroOptions to register the function. The following code is in a Class file, the function is in another module file. They would load when we open Excel and the Addin.
Code:
Private Function AddFunctions()
With MyFunction
Application.MacroOptions .Name, _
.Description, , , , , .Category, , , .HelpFilePath
End With
End Function
Expectation:
I wanna get the argument help, function description in Excel function wizard as other built-in functions. With the help button link to my help file.
Result:
Error number: 1004 Application-defined or object-defined error
or
Method "MacroOptions" of object "_Application" failed
Is there anything (or everything) wrong?
I have kind of 10 functions and need to add them automatically to Excel function wizard every time load the Addin.
07/12/2016 well after dragging my function around following pieces of advise from some posts and doing a number of other pointless things, I found this error happens if Application.MacroOptions Description:=FuncDesc exceeds 255 characters. So essentially don't get too verbose with the description of your user defined function, or just add a
If Len(FuncDesc) > 255 then
Scary warning message about Run-time error '1004'
End if
Another possible issue (and solution) that was affecting me... The function code needs to be written in a module - if it it written in the ThisWorkbook page, Excel won't be able to find the code.
For ease of future readers, here is a compilation of the multiple answers (i.e. list of potential things to check)...
The function code needs to be written in a module (not ThisWorkbook)
Make sure the function description does not exceed 255 characters
If defined in another workbook, try including the workbook name - e.g. Macro:="'PERSONAL.xlsb'!Macro/UDF_Name"
If defined in an Excel add-in, call ThisWorkbook.Activate before Application.MacroOptions
Hope this helps, please one-up the respective solution poster if their answer helped you 👍🏼
I understand that question is old, but will post my solution to this error, as it may be common and exception message is not informative.
I fixed it with passing a macro/UDF-holder workbook name into "Macro" parameter, like "'Workbook.xls(x/m/b)'!Macro/UDF_Name":
' Adding a macro from Personal.xlsb
Application.MacroOptions _
Macro:="'PERSONAL.xlsb'!Macro/UDF_Name", _
Description:="Description", _
ArgumentDescriptions:=ArgumentsDescription()
Another observation: if the Application.MacroOptions in being run from VBA add-in with ThisWorkbook.IsAddin = True e. g. from Workbook_AddinInstall or Workbook_AddinUninstall, and there is no other workbook opened, Excel throws error 1004. Problem can be solved if one calls ThisWorkbook.Activate before calling Application.MacroOptions.