ActiveWorkbook.Names.add seems to be incompatible with "Function" - vba

I have a problem with :
Function Create_Model(adress As range, name As String) As String
Dim Msg As String
On Error GoTo ErrorHandler
ActiveWorkbook.Names.add "toto", "=Interface!$I$19"
Create_Model=name
Exit Function
ErrorHandler:
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
Resume Next
End Function
Indeed, if I run this, I get :
"Error # 1004 was generated by VBAProject
Error Line: 0
Application-defined or object-defined error"
It seems that the problem come from the use of "Function" because if I try to execute this with a "Sub", it's working.
Someone could please explain me why I can't do this with a "Function" and how I could replicate this function otherwise?
P.S : If I compile using Debug->Compile VBAProject. I don't get any message.
P.S.2 : This function aims to be used in excel formula.
P.S.3 : Argument used are : adress = J18:L20 and name = "Test". And finnaly, I would like replace "toto" by name and "=Interface!$I$19" by adress.
Thanks for your help.

After the comments below, I got to thinking, and realized that my original answer (see below) is perhaps more based in (my own!) best practice than being technically correct.
The main difference between a Function and a Subroutine is that a Function can return a value, while a Subroutine cannot.
I have heard of other issues in using Function rather than Subroutine but can't find a list right now. You have apparently found one, though! These (perhaps) rumors of issues, is why I tend to limit actions to Subroutines, and returning values to Functions.
After doing some digging, I've found the following resources that may help with further explanation of the difference between the two.
From Chip Pearson's site: a page called Macros and Functions
From ExcelFunctions.net: a page called Excel VBA Tutorial Part 4 - VBA Functions & Subroutines
Looks like I learned something today.
==ORIGINAL ANSWER==
Short answer and super high-level
Functions are typically not the best place to perform actions (on a worksheet, cell, file, create objects, etc). They are really good at returning values, and that is what they are designed for.
Subs or procedures are built for taking action.
I have never seen this particular issue, but have run into many things that trying to do them in a Function causes problems.

Related

VBA crashes when trying to insert a multitude of CrossReferences

I encountered a mysterious problem when trying to run the following thing in VBA for Word:
Option Explicit
Sub Test()
Dim allHeadlines As Variant
Dim i As Integer
allHeadlines = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading) ' Gets all headlines
For i = 1 To UBound(allHeadlines)
Selection.InsertCrossReference ReferenceType:="Nummeriertes Element", _
ReferenceKind:=wdNumberRelativeContext, ReferenceItem:=Str(i), _
InsertAsHyperlink:=True, IncludePosition:=False, SeparateNumbers:=False, _
SeparatorString:=" "
Next
End Sub
The idea was simple: Just get all headlines and write them down automatically. (Actually, my intention was a bit different, but I broke the program down as much as I could.) "Nummeriertes Element" means "numbered element".
After 296 elements, the program crashes with a very unspecific error (Runtime Error '4198': "Command Failed") at the Selection.InsertCrossReference command. If I ignore the error and try to move on, Word crashes with an equally unspecific "heap damaged" error.
What also bothers me is that if I restart the Sub, it will fail immediately with Runtime Error '4198'. I have to restart Word completely to be able to run the Sub again, and then it will again crash at the same point (296 elements). Seems like some buffer is full and will not be cleared until I restart Word, but this is very annoying (I have much more than 300 headlines in this document).
I am quite at a loss here, because I do not really understand what is going on, or how to circumvent the problem. Does somebody else have an idea what is going on or what I am doing wrong?
The reason you are getting the error is you don't have a "Nummeriertes Element" reference in your document perhaps OR, more likely, you have 295 "Nummeriertes Element" in your document. When it tries to insert the reference to "Nummeriertes Element"(296), it bombs. The bombing after slamming through a couple pretty fast may just be an issue with Word (I've seen some pretty strange things happen with word and .docm corruptions). Unfortunately, you get that awful error which means absolutely nothing.
Option Explicit
Sub Test()
Dim allHeadlines As Variant
Dim doc As Document
Dim i As Integer
allHeadlines = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading) ' Gets all headlines
For i = 1 To UBound(allHeadlines)
Selection.InsertCrossReference ReferenceType:=wdRefTypeHeading, _
ReferenceKind:=wdNumberRelativeContext, ReferenceItem:=i, _
InsertAsHyperlink:=True, IncludePosition:=False, SeparateNumbers:=False, _
SeparatorString:=" "
Next i
End Sub
This will cross reference to your headings. When you specify that your ReferenceType is "Nummeriertes Element" on the backend (I assume), it is doing a GetCrossReferenceItems(wdRefTypeNumberedItem) and then you specify you want to get it by the ordinal with wdNumberRelativeContext and trying to grab GetCrossReferenceItems(wdRefTypeNumberedItem)(296) which doesn't exist.
But when you change your ReferenceType to wdRefTypeHeading it will cross reference the heading itself at the ordinal and not your numbered list items. You can the drop then str(i) to just i
Hope it helps.

MS access function vba, macro [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having a small issue while making a report in MS Access. I wrote a function in vba, and created a macro to RunCode (the function). So when I execute the Macro, it runs the function and gives me a message box. See Image..
I've researched this and tried SetWarning OFF but it keeps popping up. How do i get rid of this?
For future reference, a typical "complete" error handling structure looks e.g. like this:
Sub MySub()
On Error GoTo MySub_Err
' Stuff
MySub_Exit:
On Error Resume Next
' ... Stuff that always needs to run on exit can go here ...
' !! This is the important part that prevents the function
' !! from always running into the error handler:
Exit Sub
MySub_Err:
MsgBox Err.Description, vbExclamation, "Runtime Error " & Err.Number & " in MySub"
Resume MySub_Exit
End Sub
MZ-Tools can create this structure automatically (but customizable).
error_handler:
Error_handler:
msgbox err.number & " - " & err.description
this was giving me an error.
I did not do my error_handler: properly (error_handler:). After my function was completed, it would run into error_handler:msgbox err.number & " - " err.description and give me the message box - saying "0 - " because there was no error. I commented it out and everything seems to work okay. Thanks to #HansUp and everyone else for their help.

SSIS Element cannot be found in a collection (but I have them all listed!)

I'm getting a persistent error:
The element cannot be found in a collection.
This error happens when you try to retrieve an element from a collection on a container during execution of the package and the element is not there.
I've checked, double and triple-checked my variable listings in the Read-Only and Read-Write variables in my Script task.
I've debugged it to death and gotten input from another programmer here who couldn't spot the issue either.
I've also researched to no end.
Does anyone see anything wrong with my code?
Script Task code:
Public Sub Main()
Dts.Variables("User::strMailBody").Value = "Thank you for submission. For your convenience, we are including the last four of the HICN# and the Name on the application(s) we have received* from you." _
& vbNewLine & vbNewLine & "Here are the following: " & vbNewLine & vbNewLine
Dts.Variables("User::strMailBody").Value = Dts.Variables("User::strMailbody").Value.ToString() & vbNewLine & Dts.Variables("User::strListing").Value.ToString()
Dts.Variables("User::strMailBody").Value = Dts.Variables("User::strMailBody").Value.ToString() & vbNewLine & vbNewLine & Dts.Variables("User::strFooter").Value.ToString()
If Left(Dts.Variables("User::strAgentID").Value, 2) = "TX" Then
Dts.Variables("User::strSubject").Value = "ACME Health Plans Confirmation: Total "
Else
Dts.Variables("User::strSubject").Value = "ACME2 Baptist Health Plans Confirmation: Total "
End If
Dts.Variables("User::strSubject").Value = Dts.Variables("User::strSubject").Value.ToString() & Dts.Variables("User::lngCountAgent").Value.ToString() & " " & "[RESTRICTED: CONFIDENTIAL]"
Dts.Variables("User::DateSent").Value = Now()
Dts.Variables("User::UserSent").Value = "SSIS"
Dts.TaskResult = ScriptResults.Success
End Sub
For anybody else struggling with this issue the resolution for me was as follows: (note I am NOT using User:: when getting variable values within my script task)
On the package Properties I hadn't included the variables as ReadOnlyVariables
You'll need to set your newly added variables as follows:
Right click on the package and select Edit
In the Script section click on ReadOnlyVariables or ReadWriteVariables (depending on your how you want your variables behave)
Check the check-box beside the variables you wish to use in your script task
Click Ok to save your changes
Hope this helps
I just had the same issue and unable to find the problem for ages. I found that the reason for the error was that I had missed one of the colons between "User" and the variable name.
I had this (which caused the error):
string FileName = UserVariables["User:CurrentFileName"].Value.ToString();
when I should have had this:
string FileName = UserVariables["User::CurrentFileName"].Value.ToString();
just in case anyone else has the same problem :)
Ohhh.........man. It's amazing how you can stare at this stuff and miss something stupid, for hours.
strFooter was missing in the listing.
ALL SET NOW. Sincere thanks to those who looked and commented. Eric, thanks, I'll remember that as sometimes I will probably need to use C insatead of VB (haven't yet but will).
Had a similar issue, after a lot of debugging, realized that the variable naming convention should be User::varname and NOT USER::varname
I guess c# is very case sensitive.
Hope this helps and saves you lot of your valuable time :-)
a) Right click on the script task and choose edit
b) Locate the Read or Read/Write variables properties in the list.
c) Click on the property and the variable you wish to access in the script task.
Another variation on "have been staring at the screen for too long to see the typo". In my case, I got the same error by mixing up the syntax between Project Params and User variables, and adding a $ sign in front of User.
error :
string varA = (string)Dts.Variables["$Project::ParamA"].Value
string varB = (string)Dts.Variables["$User::ParamB"].Value
corrected :
string varA = (string)Dts.Variables["$Project::ParamA"].Value
string varB = (string)Dts.Variables["User::ParamB"].Value

QTP, Unspecified Error when calling a specific function

I'm facing a problem with QTP 11 (Quick Test Professional), the problem occurred when trying to call some function, QTP display a run time error ("General run error.") poopup message box.
i had tried many time to resolve the issue, but I dont understand what exactly causing the error.
when i Call a function from "Function library" the error displays. unless i took this function to an Action then the function will work.
have any one faced issue like this ?
Any help would be appreciated!
Sometimes I get the "General Run Error" error when I am attempting to call a function and pass the incorrect number of parameters in the function call.
Can you explain your last paragraph some more? When you run the function via FL, it works? You should not be running functions directly in your FL, but inside of your actions.
Here's an example:
Action
test_function("Hello", "42")
test_function(42, "Hello")
Function Library
Function test_function(sTextString, iIntNumber)
iNewIntNumber = iIntNumber + 1
MsgBox "String: " & sTextString & vbNewLine & "Int + 1: " & iNewIntNumber
End Function
In my function library, the second line (iNewIntNumber = iNewIntNumber + 1) may throw a "General Run Error" in the action due to an invalid cast on the variable.

How to display value from cell in vba code?

Row_No = 5
MsgBox Range.("A & Row_No").value
i have above code but it gives me error 1004..please help me with this.
Just try this
MsgBox Range.("A" & Row_No).Value
or this
MsgBox Range.("A" & Row_No).Text
or this
MsgBox Cells(1,"C")
Problem with the code you used is nothing but placing of & and " in wrong place.
Hope this helps.
When doing concatenation, keep in mind that strings will be in quotes and variables will not -- think of the quotes as telling the compiler to interpret what is between them as literal text. A good IDE will usually indicate this via syntax highlighting.
So, in your code, the Range() method is being passed the string A & Row_No instead of A5 -- so it errors out.