Consulting

Results 1 to 2 of 2

Thread: coverting if formula to macro

  1. #1
    VBAX Newbie
    Joined
    Jan 2019
    Posts
    1
    Location

    coverting if formula to macro

    Hi
    I need help converting this formula to a macro

    Formula :=IF(LEN(A2)=6,"XXX-0000"&A2,A2)

    for example if i have "121213" in col A2, I would like to have a code that will count the characters in the cell, confirm it has 6 characters in the cell, and then if it is 6, i would like it to become "XXX-000012123". if not 6 characters, i want it to leave it as is
    The formula above will do this, i just dont know how to convert it to a macro.

    Thank you

  2. #2
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,724
    Location
    Attached show how the little AddPrefix function below can be used on a worksheet as well as part of another macro

    Six is hard coded but you could easily make it an Optional parameter like 'Prefix' for flexibility


    This goes on a Standard Module

    Option Explicit
    
    Function AddPrefix(X As Variant, Optional Prefix As String = "XXX-0000") As Variant
        AddPrefix = X
        If Len(CStr(X)) = 6 Then AddPrefix = Prefix & X
    End Function
    
    Sub UsedInMacro()
        MsgBox AddPrefix("ABC")
        MsgBox AddPrefix("ABCABC")
        MsgBox AddPrefix("ABCABC", "ZZYYXX-WWVV")
        MsgBox AddPrefix(123)
        MsgBox AddPrefix(123456)
    End Sub
    Attached Files Attached Files
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •