PDA

View Full Version : coverting if formula to macro



junebug
01-31-2019, 09:47 AM
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

Paul_Hossler
01-31-2019, 10:02 AM
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