简体   繁体   中英

Excel macro to normalize data

I am currently trying to create a macro for Excel in which a column containing certain values (numbers basically) will be displayed in a new column in a normalized way (highest number = 1, lowest number = 0).

Usually, I would just use the formula:

=(J2-MIN($J$2:$J$XXX))/(MAX($J$2:$J$XXX)-MIN($J$2:$J$XXX))

However, as the length of the column is dynamic and will change for each set of values, I cannot enter a value for XXX.

Now, I found out how to have a dynamic range (eg: numRows = Range(Selection, Selection.End(xlDown)).Rows.Count ) but I did not manage to merge both functions.

I found a thread already in this site about normalization of data but I think it was a bit of a different story and this one here should be simpler.

I would appreciate any help! As I just started working with macros (2h ago) I would also appreciate if this will be in simple language.

EDIT: First of all, thanks for the quick reply!

I naively tried making it work with this code:

Sub Normalize_TEST()
'
' Normalize_TEST Makro
'

'
    Range("A1").Select
    numRows = Range(Selection, Selection.End(xlDown)).Rows.Count
    Range("K2").Select
    ActiveCell.FormulaR1C1 = "=(("J2")-MIN($J$2:$J$numRows$))/((MAX($J$2:$J$numRows$)-MIN($J$2:$J$numRows$))
    Range("K2").Select
    Selection.AutoFill Destination:=Range(Cells(2, 11), Cells(numRows, 11))
End Sub

But it is not working and I get an error message ("error of compiling").

I just realize now that you are absolutely right, I don't even need VBA. Your line of =(J2-MIN($J:$J))/(MAX($J:$J)-MIN($J:$J)) works fine. I wasn't aware that with $j:$J it realizes to not include empty cells. I simply used this code now for cell K2 and then did a VBA autofill function for the rest. I think this can be closed.

Thank you @tigeravatar for your super quick help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM