How to call a procedure depending on a cell value - excel

Please Help,
I have written different procedures on different worksheet in a Workbook. I want to call a particular procedure depending on the specific cell value in a worksheet.
I tried with defining a variable
Example:
Private Sub CommandButton1_Click()
pbk = Me.Range("L1").Value
Call pbk
End Sub
but I'm getting errors like this:
Microsoft Visual Basic for Applications
Compile error:
Expected Sub, Function, or Property
value Range L1 is changing as per contents it has array of total 15 contents, so I have written 15 procedures different. i just need to call each procedure depending on the value of 'L1'.
Its total 15 Procedures, i can write with the IF condition like this:
Private Sub CommandButton1_Click()
pbk = Me.Range("L1").Value
If pbk = "PBK_Kirim" Then
Call PBK_Kirim
End If
If pbk = "PBK_ke_Masa" Then
Call PBK_ke_Masa
End If
'and so on
End Sub
but it will be too bulky so i'm trying for some easy method. thanks before

I agree with Rory, use "run pbk". Only other alternative to clean it up without using run that I can think of is build another sub routine passing in the pbk value and using select case for the different calls.

Related

Pass subroutine name as string to use subs as general purpose input validation

I read through several posts about similar problems and tried many solutions offered by this and other communities. I cannot tailor any of these to my specific needs.
I have an Excel workbook that generates a timesheet and a detailed job report based on the information provided in a userform.
The job report and the timesheet are exported to an Access table (or imported from said table to be edited or deleted).
I have a working version with repetitive code for validating the userform inputs.
There are eight inputs that must meet criteria.
i) must be a number
ii) must not be less than a minimum value
iii) must not be greater than a maximum value
I have a subroutine for each of these inputs that checks these criteria using BeforeUpdate, and calls another subroutine to make visible changes to the userform to alert the user of an invalid entry (alter the label color and caption, textbox or dropbox color, etc.).
Using AfterUpdate, I have a subroutine for each of the eight inputs that reverts these changes once a valid entry has been made.
This means I have 24 subroutines with basically the same code, where I feel there should only be three subroutines that can be used more generally.
Here is the code I have for these subroutines, as it is being used for one specific input:
Sub #1
Private Sub NumberOfTechs_BeforeUpdate(ByVal CAncel As MSForms.ReturnBoolean)
If Not IsNumeric(numberOfTechs) Then
Call NumberOfTechsInvalid("Must be a number!", numberOfTechsLabel, numberOfTechs)
CAncel = True
Else
If numberOfTechs < 1 Then
Call NumberOfTechsInvalid("Cannot be less than 1!", numberOfTechsLabel, numberOfTechs)
CAncel = True
ElseIf numberOfTechs > 6 Then
Call NumberOfTechsInvalid("Cannot exceed 6!", numberOfTechsLabel, numberOfTechs)
CAncel = True
End If
End If
End Sub
Sub #2
Private Sub NumberOfTechsInvalid(errorCaption As String, targetLabel As Object, targetControl As Object)
targetLabel.caption = errorCaption
targetLabel.ForeColor = rgbRed
targetControl.BackColor = rgbPink
targetControl.SelStart = 0
targetControl.SelLength = Len(targetControl)
End Sub
Sub # 3
Private Sub NumberOfTechs_AfterUpdate()
numberOfTechsLabel.ForeColor = Me.ForeColor
numberOfTechsLabel = "Number Of Techs"
numberOfTechs.BackColor = rgbWhite
' Call next subroutine
End Sub
I have a comment at the bottom of sub#3 that says "call next subroutine". This is where I am having difficulty.
I can pass the minimum and maximum values as variables, as well as specify the target control and label based on which user input triggers the call to sub#1.
The issue is passing the next subroutine as a string.
I tried placing these subroutines in their own module and using Application.Run. I tried using CallByName with these subs within the userform code.

Excel VBA - Use an existing string in called sub

I'm pretty new to this so apologies in advance
I'm half way through a userform in Excel and I'm trying to cut some fat off my code by using Call - I have 12 buttons that all do the same thing, the only difference is that each buttons sub is dependant on the buttons caption. My problem is that I can't figure out a way to use a String I've already declared in the Buttons Sub, then use it in the called Sub. I know you can do it, but my googling skills have failed me :(
Please could someone show me how to do this? Hope that all makes sense...
Here is a very small snippet of my code, but you get the jist:
Public Sub CommandButton4_Click()
Dim Name As String
Name = CommandButton4.Caption
Call Sort1
End Sub`
And the other one (Also tried this as function for the sake of trial and error)
Public Sub Sort1(Name As String)
Label11.Caption = Name
Sheets(Name).Select
End Sub
What you're referring to is passing an argument to another subroutine or function. Let's say you want to use a function a lot of times to get the first letter of a string. A sample of this is:
Function LeftOne(StrSample As String) As String
LeftOne = Left(StrSample, 1)
End Function
The above function can be used inside another function or subroutine provided you meet its requirement: StrSample. By declaring StrSample As String in the arguments field of the function, you are basically requiring that any calls to this should require a string to be passed to it. Anything else would throw an error.
The full line LeftOne(StrSample As String) As String can be read as: "I am function LeftOne. Pass me a string and I'll return to you a string after doing something with it." Note that the name StrSample is an arbitrary name.
Anyway, calling the above is as simple as:
Sub MsgInABox()
Dim StrToFeed As String
StrToFeed = "BK201"
MsgBox LeftOne(StrToFeed) 'Returns B.
End Sub
In your example, if you want to pass Name to Sort1, your attempt is absolutely correct.
Let us know if this helps.
You hat to give your sort1 procedure the parameter name.
call sort1(name)
or
call sort1(CommandButton4.Caption)

Lock Select Box Size In Excel

This seems like a simple thing, but I cannot figure it out, or find it online.
If I select 5 cells in a column(say A1:A5), and I would like to move this selection shape(column 1:5) over (to B1:B5); Is there shortcut to do this? Currently I hit the left arrow, and the select box changes size to just B1, and I have to hit shift and select B2:B5. Ideally I would like to discover a hot key that "locks" the shape of the select box.
It has been suggested by colleagues to write a macro, but this is ineffective in many cases. For example what if instead of a column I wanted to do the same thing with a row, or with a different sized shape. It seems likely that excel has this feature built in.
I'm not sure how a macro would be ineffective. I would write procedures similar to what's below, then assign them to hotkeys. Let me know if it works for you.
Option Explicit
Public rowDim As Long
Public colDim As Long
Public putSel as Boolean
Sub togglePutSel()
putSel = Not putSel
End Sub
Sub GetSelShape()
rowDim = Selection.Rows.Count
colDim = Selection.Columns.Count
putSel = True
End Sub
Sub PutSelShape()
Selection.Resize(rowDim, colDim).Select
End Sub
If you want to make it work for whenever you hit the arrow keys, then in your Sheet code, you can use this. You may want to do a quick check that rowDim and colDim aren't 0. The only issue with this is that you'd be stuck with that behavior unless you create a trigger to stop calling PutSelShape. So, I'd suggest one macro (hotkeyed to GetSelShape) to toggle it, and another hotkey for togglePutSel.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If putSel Then
Call PutSelShape
End If
End Sub

How do you GoTo a line label in a different object?

E.g. Given Sheet 1 contains:
Ref: Do things
How can I direct a code in Module 1 to GoTo Ref? If I were in the Sheet1 code moduke then I could simply use a
Goto Ref
But this doesn't work across different modules
Your question is not clear and you didn't provide any code, so this is a guess.
GoTo is used to jump to different locations within the same sub/function. You cannot use it to jump to parts of other sub routines or functions, which it sounds like you might be trying to do.
Also, "NapDone:" is not called a reference, it's formally called a line label. :)
To help expand on the other answers.. Like they said you shouldn't use GoTo for anything in VBA except error handling.
What you should be doing is calling a public sub/function from another module. For example in Module 1 you would have the following
Sub TestMod1()
Dim MyNumber As Integer
MyNumber = GetSquare(6)
'MyNumber returns from the function with a value of 36
End Sub
and on Module 2 you have
Public Function GetSquare(ByVal MyNumber As Integer)
GetSquare = MyNumber * MyNumber
End Function
So now you know how to avoid it. GoTo is not very good programming practice as you'll have things flying all over the place. Try to break down code you're repeating into multiple Subs and just call them when needed, or functions whatever be the case. Then you'll get into classes, which are just wrapped up to represent an object and it'll do all the work for that object.
This should get you on the right track.

Stop VBA Evaluate from calling target function twice

I am having trouble getting VBA's Evaluate() function to only execute once; it seems to always run twice. For instance, consider the trivial example below. If we run the RunEval() subroutine, it will call the EvalTest() function twice. This can be seen by the two different random numbers that get printed in the immediate window. The behavior would be the same if we were calling another subroutine with Evaluate instead of a function. Can someone explain how I can get Evaluate to execute the target function once instead of twice? Thank you.
Sub RunEval()
Evaluate "EvalTest()"
End Sub
Public Function EvalTest()
Debug.Print Rnd()
End Function
This bug only seems to happen with UDFs, not with built-in functions.
You can bypass it by adding an expression:
Sub RunEval()
ActiveSheet.Evaluate "0+EvalTest()"
End Sub
But there are also a number of other limitations with Evaluate, documented here
http://www.decisionmodels.com/calcsecretsh.htm
I don't know of a way to stop it, but you can at least recognize when it is happening most of the time. That could be useful if your computation is time consuming or has side effects that you don't want to have happen twice and you want to short circuit it.
(EDIT: Charles Williams actually has an answer to your specific quesion. My answer could still be useful when you don't know what data type you might be getting back, or when you expect to get something like an array or a range.)
If you use the Application.Caller property within a routine called as a result of a call to Application.Evaluate, you'll see that one of the calls appears to come from the upper left cell of of the actual range the Evaluate call is made from, and one from cell $A$1 of the sheet that range is on. If you call Application.Evaluate from the immediate window, like you would call your example Sub, one call appears to come from the upper left cell of the currently selected range and one from cell $A$1 of the current worksheet. I'm pretty sure it's the first call that's the $A$1 in both cases. (I'd test that if it matters.)
However, only one value will ever be returned from Application.Evaluate. I'm pretty sure it's the one from the second eval. (I'd test that too.)
Obviously, this won't work with calls made from the actual cell $A$1.
(As for me, I would love to know why the double evaluation happens. I would also love to know why the evaluator is exposed at all. Anyone?)
EDIT: I asked on StackOverflow here: Why is Excel's 'Evaluate' method a general expression evaluator?
I hope this helps, although it doesn't directly answer your question.
I did a quick search and found that others have reported similar behavior and other odd bugs with Application.Evaluate (see KB823604 and this). This is probably not high on Microsoft's list to fix since it has been seen at least since Excel 2002. That knowledge base article gives a workaround that may work in your case too - put the expression to evaluate in a worksheet and then get the value from that, like this:
Sub RunEval()
Dim d As Double
Range("A1").Formula = "=EvalTest()"
d = Range("A1").Value
Range("A1").Clear
Debug.Print d
End Sub
Public Function EvalTest() As Double
Dim d As Double
d = Rnd()
Debug.Print d
EvalTest = d + 1
End Function
I modified your example to also return the random value from the function. This prints the value a second time but with the one added so the second print comes from the first subroutine. You could write a support routine to do this for any expression.
I face the same problem, after investigation i found the function called twice because i have drop down list and the value used in a user defined function.
working around by the code bellow, put the code in ThisWorkbook
Private Sub Workbook_Open()
'set the calculation to manual to stop calculation when dropdownlist updeated and again calculate for the UDF
Application.Calculation = xlCalculationManual
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, _
ByVal Source As Range)
'calculte only when the sheet changed
Calculate
End Sub
It looks like Application.Evaluate evaluates always twice, while ActiveSheet.Evaluate evaluates once if it is an expression.
When the object is not specified Evaluate is equivalent to Application.Evaluate.
Typing [expression] is equivalent to Application.Evaluate("expression").
So the solution is to add ActiveSheet and to make that an expression by adding zero:
ActiveSheet.Evaluate("EvalTest+0")
After seeing there is no proper way to work around this problem, I solved it by the following:
Dim RunEval as boolean
Sub RunEval()
RunEval = True
Evaluate "EvalTest()"
End Sub
Public Function EvalTest()
if RunEval = true then
Debug.Print Rnd()
RunEval = False
end if
End Function
problem solved everyone.

Resources