VBA code to add 0 if len is different

jbesclapez

Active Member
Joined
Feb 6, 2010
Messages
275
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
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
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))
 
Upvote 0

Forum statistics

Threads
1,215,039
Messages
6,122,802
Members
449,095
Latest member
m_smith_solihull

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
Back
Top