1

I'm trying to program a Command button in Excel VBA that can call on specific macros based on the string value of a cell. I thought I can just use conditional "if" statements, but there is a bug in the program.

For example, so far I have:

Private Sub CommandButton1_Click()
    If Range("F3").Select = "Retirement Age" Then
        Call NewRA
    End If
End Sub

And I want the Button to run the macro named "NewRA" when Cell F3 equals "Retirement Age". How can I write the code appropriately to this? Thanks in advance.

2 Answers 2

4

To start, I recommend using Range("F3").Value rather than Range("F3").Select.

From there, if you plan on having more than two scripts hooked to this button, I would read up on the Select Case construct. Here's an MSDN link: http://msdn.microsoft.com/en-us/library/cy37t14y.aspx

For example:

'... do your setup here

Select Case CStr(Range("F3").Value) '<~ convert whatever is in cell F3 to a String
    Case "Retirement Age"
        Call NewRA
    Case "Another String"
        Call AnotherStringScript
    Case "Another, Even Cooler String"
        Call AnotherEvenCoolerString
    '...
    Case Else
        Msgbox ("Hey! The value in this cell doesn't match a script!")
End Select
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Range("F3").value , or Range("F3").value2 , or Range("F3").text, or even without a dot Range("F3") , but "never" use .select or .activate (unless no other choice, wich is rare in VBA)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.