VBA code to add 0 if len is different

jbesclapez

Board Regular
Joined
Feb 6, 2010
Messages
235
Hello,

I am trying to build a VBA that would :
1- Check the lastrow in A
2- From D2:D lastrow it will give me the MAX of LEN of this array (max nb of character value)
3- Go on all cells from D2:D lastrow and add a 0 at the end of the cellvalue if the LEN of this cell value is less than the value in 2 (MAX LEN of array)

So far I am struggling with something stupid : I do not know how to have my formula work in the VB!!!

Thanks for your help

VBA Code:
Public Function maxRangeLength(data As Range) As Integer 'USAGE =maxRangeLength(A8:D11)
    Dim ret As Integer

    ret = 0

    For Each cell In data
        ret = Application.max(ret, Len(cell))
    Next cell

    maxRangeLength = ret
End Function

Sub ReformatID()

Dim sht As Worksheet
Dim LastRowA As Integer
Dim MaxLenD As Integer

Set sht = ActiveSheet

LastRowA = sht.Cells(sht.Rows.Count, "A").End(xlUp).row
MaxLenD = maxRangeLength("D2:D" & LastRowA)

End Sub
 

Some videos you may like

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December

rlv01

Well-known Member
Joined
May 16, 2017
Messages
771
VBA Code:
MaxLenD = maxRangeLength("D2:D" & LastRowA)
Function maxRangeLength expects a range parameter, but you are giving it a string. Try this instead:
VBA Code:
 MaxLenD = maxRangeLength(Range("D2:D" & LastRowA))
 

Watch MrExcel Video

Forum statistics

Threads
1,127,867
Messages
5,627,354
Members
416,244
Latest member
JBKool

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top