VBA: Run-time error '5825' Object has been deleted - vba

I was putting this code ActiveDocument.Variables("time1").Delete before End Sub and I get that error "Object has been deleted" so that if a variable "time1" exist, it will be deleted at the end of the procedure. I understand why I get that code because "time1" has already deleted on the first run but I want to skip and end the sub if it encounter errors. I tried to do this
On Error Goto here
ActiveDocument.Variables("time1").Delete
here:
End sub
but I still get that Error. Why is it that the error handler did not work?

You should be able to avoid this if you are not interested in whether the Variable existed or not.
ActiveDocument.Variables("time1") = ""
should remove a Variable called "time" if there is one, and execute without errors if there is not.
In a similar way,
ActiveDocument.Variables("time1") = "something"
will create the Variable if it does not exist.
This is one of the things that makes Variables slightly easier to work with than Custom Document Properties, although it does mean that empty variables are not allowed.

Related

Input box getting a compile error in VBA

I am learning how to create input boxes and I keep getting the same error. I have tried two different computers and have received the same error. The error I get is a "Compile Error: Wrong number of arguments or invalid property assignment"
Here is my code:
Option Explicit
Sub InputBox()
Dim ss As Worksheet
Dim Link As String
Set ss = Worksheets("ss")
Link = InputBox("give me some input")
ss.Range("A1").Value = Link
With ss
If Link <> "" Then
MsgBox Link
End If
End With
End Sub
When I run the code, it highlights the word "inputbox"
And help would be greatly appreciated.
Thanks,
G
Three things
1) Call your sub something other than the reserved word InputBox as this may confuse things. *Edit... and this alone will resolve your error. See quote from #Mat's Mug.
2) A̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶.̶I̶n̶p̶u̶t̶B̶o̶x̶(̶"̶g̶i̶v̶e̶ ̶m̶e̶ ̶s̶o̶m̶e̶ ̶i̶n̶p̶u̶t̶"̶)̶ Use VBA.Interaction.InputBox("give me some input"). You can do this in addition to the first point. Documentation here.
3) Compare with vbNullString rather than "" . See here. Essentially, you will generally want to do this as vbNullString is, as described in that link, faster to assign and process and it takes less memory.
Sub GetInput()
Dim ss As Worksheet
Dim Link As String
Set ss = Worksheets("ss")
Link = VBA.Interaction.InputBox("give me some input")
ss.Range("A1").Value = Link
' With ss ''commented out as not sure how this was being used. It currently serves no purpose.
If Link <> vbNullString Then
MsgBox Link
End If
' End With
End Sub
EDIT: To quote #Mat's Mug:
[In the OP's code, what is actually being called is] VBA.Interaction.InputBox, but the call is shadowed by the procedure's identifier "InputBox", which is causing the error. Changing it to Application.InputBox "fixes" the problem, but doesn't invoke the same function at all. The solution is to either fully-qualify the call (i.e. VBA.Interaction.InputBox), or to rename the procedure (e.g. Sub DoSomething(), or both.
Sub InputBox()
That procedure is implicitly Public. Presumably being written in a standard module, that makes it globally scoped.
Link = InputBox("give me some input")
This means to invoke the VBA.Interaction.InputBox function, and would normally succeed. Except by naming your procedure InputBox, you've changed how VBA resolves this identifier: it no longer resolves to the global-scope VBA.Interaction.InputBox function; it resolves to your InputBox procedure, because VBAProject1.Module1.InputBox (assuming your VBA project and module name are respectively VBAProject1 and Module1) are always going to have priority over any other function defined in any other referenced type library - including the VBA standard library.
When VBA resolves member calls, it only looks at the identifier. If the parameters mismatch, it's not going to say "hmm ok then, not that one" and continue searching the global scope for more matches with a different signature - instead it blows up and says "I've found the procedure you're looking for, but I don't know what to do with these parameters".
If you change your signature to accept a String parameter, you get a recursive call:
Sub InputBox(ByVal msg As String)
That would compile and run... and soon blow up the call stack, because there's a hard limit on how deep the runtime call stack can go.
So one solution could be to properly qualify the InputBox call, so that the compiler knows exactly where to look for that member:
Link = VBA.Interaction.InputBox("give me some input")
Another solution could be to properly name your procedure so that its name starts with a verb, roughly describes what's going on, and doesn't collide with anything else in global scope:
Sub TestInputBox()
Another solution/work-around could be to use a similar function that happens to be available in the Excel object model, as QHarr suggested:
Link = Application.InputBox("give me some input")
This isn't the function you were calling before though, and that will only work in a VBA host that has an InputBox member on its Application class, whereas the VBA.Interaction.InputBox global function is defined in the VBA standard library and works in any VBA host.
A note about this:
If Link <> "" Then
This condition will be False, regardless of whether the user clicked OK or cancelled the dialog by "X-ing out". The InputBox function returns a null string pointer when it's cancelled, and an actual empty string when it's okayed with, well, an empty string input.
So if an empty string needs to be considered a valid input and you need to be able to tell it apart from a cancelled inputbox, you need to compare the string pointers:
If StrPtr(Link) <> 0 Then
This condition will only be False when the user explicitly cancelled, and will still evaluate to True if the user provided a legit empty string.

Access TempVars Don't Compile

I've used TempVars for some time, but am having some issues with one set in an Access 2010 database.
Whenever I try to compile, an error dialog stating "Method or data member not found" appears and the term TempVars is highlighted.
Here's the code snippet in question:
If TempVars("Connected") And TempVars("HasAccessBE") And Me.chkBackupOnExit Then MakeBackup
While I've successfully used TempVars("xx") previously where "xx" is the variable which has been defined elsewhere with TempVars.Add "xx", "yy"
In this instance the compiler somehow thinks TempVars isn't viable code.
These have been checked as well:
Application.TempVars("xx")
TempVars.Item("xx")
Search for user defined variables named TempVars (none found)
Desired variable has been defined via TempVars.Add "xx", "yy" (it was)
In case this is a corruption thing, the following tasks have also been completed:
Database Compact & Repair
Database Decompile
I'm trying to resolve this so I can compile and move forward. The code functions fine for users, however it still needs to be compiled.
Any ideas on how to resolve the issue?
Very interesting behavior.
This compiles for me:
If TempVars("Connected") And TempVars("HasAccessBE") Then Debug.Print "Yay!"
If the TempVars don't exist, I will get a runtime error, not a compile error.
Actually not even this, they just return Null.
This does not compile:
If TempVars("Connected") And TempVars("HasAccessBE") Then WrongFunction
but: The compiler selects the first TempVars and says "Sub or Function not defined". Instead of selecting WrongFunction where the problem is.
=> The error is not in TempVars, but in the rest of the statement.
Judging from the error message, I'd say that Me.chkBackupOnExit does not exist / is spelled wrong.
Edit: To see what's going on, change your code line to
If Me.chkBackupOnExit Then MakeBackup
and try to compile this.
When adding to TempVars collection, you need to define the name and value. Then you can retrieve the value by name.
TempVars.Add(name As String, value)
Working example:
Sub Test()
Dim b As Boolean
b = True
TempVars.Add "bool", b
Debug.Print TempVars("bool")
End Sub
'True

Why does my comparator not work after first loop?

I have a pretty simple If Else statement in my code that looks like this:
If GUI.editedFH = "" Then
fhNumField.Value = fhNumField.List(0)
Else
fhNumField.Value = editedFH
End If
This block of code is in a UserForm_Initialize() sub that I call fairly often after users use the form to edit or delete rows of data. I unload the form and reload it as a way to "refresh" the data presented in the form.
The code fails at the first line in that If statement. VBE throws this error
Run-time error '1004':
Application-defined or object-defined error
GUI.editedFH is a global string that is declared in a separate module. GUI is the name of the module, and editedFH is the string variable name. I put a watch on GUI.editedFH and I'm getting String as the type and the value that I want.
When I hardcode string values in, instead of GUI.editedFH, it still doesn't work i.e.
If "abc" = "" Then
'....
End If
The part that is most confusing is that I can compare strings like this elsewhere, and it is seemingly random on when the error will throw. It will work the first time through the initialize and a few subsequent times, but eventually it will throw an error.

Error on ActiveSelection.Tasks

Does anyone know what this means
Set oProjTasks = ActiveSelection.Tasks
I have a macro that generates status reports from MS project and exports them directly into MS Word. It is a slick tool when it works.
When I run it now it throws "runtime error '424': object required" at this point.
How do I fix this?
The code that you are displaying is a set statement, that is setting the object ProjTasks equal to the task that is selected in the message box. The ActiveSelection property returns a selection object that represents the active selection.
It could be that you are experiencing an issue where there are no items selected, in which case it will throw a trappable error code 424. There is a code snippet that you can modify from the MSDN that will work to prevent this type of error from occuring.
Here is the link to the MSDN article... just remember to not use this code verbatim, but modify it to work with your macro.
http://msdn.microsoft.com/en-us/library/aa169315%28v=office.11%29.aspx
You could try just wrapping the error check around the set statement. I've written a small macro on a non-empty project file:
Sub Testing()
On Error GoTo ActiveSelectionErrHandler:
Set oProjTasks = ActiveSelection.Tasks
If oProjTasks Is Nothing Then
MsgBox "No tasks in current project"
End If
ActiveSelectionErrHandler:
Set oProjTasks = ThisProject.Tasks 'or something like that
Resume Next
End Sub
This handles the error but as Steve has already expressed more work is required to integrate the code.
You will have to follow the code to make changes to handle oProjTasks being empty where it is expected to have some values. Otherwise you will see more errors perhaps where the oProjTasks is found to be empty.
Another alternative solution could be to launch the macro after selecting a project as the code you have quoted will work fine if something is selected.

How to check if a Paragraph is in a Table or not in MS-Word macro?

The paragraph object in the Word has a property called Range. Within this Range object has a property called Cells.
For paragraph that are not in a table, this property Paragraph.Range.Cells is set to "". This can be seen in the Watches window in debug mode.
For paragraph that are in a table, the property Paragraph.Range.Cells has other properties in it, for example it has a property called Count.
I am using this property of Paragraph.Range.Cells to determine if the paragraph is in a table or not. However, I cant seem to figure out how to test this.
For example, I cannot simply test like this...
If paragraph.Range.Cells <> Null Then.... or even
If IsNull(paragraph.Range.Cells) Then ...
It throws a Run-time error '5907' There is no table at this location
So, how would I test for this? thanks
You can use the Information property:
If Selection.Information(wdWithInTable) Then
'What ever you'd like to do
End If
Hence you don't need any manual error catching mechanisms.
You can't call the Cells method unless the paragraph is in a table. You need to use a different method to determine whether the range is in a table.
You can use either...
paragraph.Range.Tables.Count > 0
...or...
paragraph.Range.Information(wdWithinTable)
Note that the second one looks more obvious, but is actually slower (only a problem if you're doing this inside a loop).
*Edited (if Err=) changed to (If Err<>)
You can simply allow the error to happen and catch it using OnError statement
Dim ParagraphIsTable As Object
OnError Resume Next 'allows errors to happen but execute next instruction
ParagraphIsTable = paragraph.Range.Cells
If Err <> 5907 Then '(this is to check for a specific error that might have happened)
'No Error occured, this means that ParagraphIsTable variable must contain a value
' Do the rest of your code here
Else
' an Error occured, this means that this is not a table
' do whatever
End If
OnError Goto 0 ' This cancels the effect of OnError Resume Next
' Which means if new errors happen, you will be prompt about them