VBA Correlation matrix with Paramarray

kisslaszlo123

New Member
Joined
Apr 16, 2020
Messages
7
Office Version
  1. 365
Platform
  1. Windows
Hello,

I have an excel sheet with multiple columns and I need to create correlation matrix for some columns that are not necessarily next to each other. I tried to replace the range with paramarray in an UDF, but didn't work and I have no idea about how to solve this problem.

Function CorrelationMatrix(ParamArray rng() As Variant) As Variant
Dim i As Integer
Dim j As Integer
Dim NumColumns As Integer

NumColumns = rng().Columns.Count - 1

Dim matrix() As Double
ReDim matrix(NumColumns, NumColumns)

For i = 0 To NumColumns
For j = i To NumColumns
matrix(i, j) = WorksheetFunction.Correl(rng().Columns(i + 1), rng().Columns(j + 1))
Next j
Next i
CorrelationMatrix = matrix
End Function

Thanks for your help in advance!
L.
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Welcome to the forum!

You're trying to use methods that don't belong to the objects you're using. Try this:

VBA Code:
Function CorrelationMatrix(ParamArray rng() As Variant) As Variant
Dim i As Long
Dim j As Long
Dim matrix() As Double

    ReDim matrix(0 To UBound(rng), 0 To UBound(rng))

    For i = LBound(rng) To UBound(rng)
        For j = i To UBound(rng)
            matrix(i, j) = WorksheetFunction.Correl(rng(i), rng(j))
        Next j
    Next i
    
    CorrelationMatrix = matrix
End Function

Book1
BCDEFGHIJKLM
21120.510.832050.9722720.892844
32334010.6864060.923851
435440010.79524
543640001
65767
7
Sheet13
Cell Formulas
RangeFormula
J2:M5J2=correlationmatrix(B2:B6,D2:D6,G2:G6,H2:H6)
Press CTRL+SHIFT+ENTER to enter array formulas surrounded with curly braces.
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,169
Members
453,021
Latest member
Justyna P

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