First tip:
In line Dim col1, col2, row1, row2 As Long
- only row2
declared as Long
, but other variables are Variant
.
You should use Dim col1 As Long, col2 As Long, row1 As Long, row2 As Long
instead. The same for other declarations.
Second tip: in line Rng1.Cells(row1 + i - row1, col1)
- expression row1 + i - row1
is always equals to i
Third tip: when you are using Rng1.Cells(row1 + i - row1, col1)
it works like offset i-1
to the bottom and col1-1
to the right from top left cell of Rng1
.
So for D2:D61
range col1
would be equals to 4
and that's means that Rng1.Cells(1, col1)
would be G2
(offset to the bottom 1-1
and to the right 4-1
from D2
) and it's not what you're expecting.
Try this function instead:
Function HCP(Rng1 As Range, Rng2 As Range) As String
' this function will take columns of data and properly format them for highcharts
Dim retVal As String
Dim i As Integer
'if ranges doesn't contains one column and same rows count - return #VALUE error
If Rng1.Rows.Count <> Rng2.Rows.Count Or _
Rng1.Columns.Count <> 1 Or Rng2.Columns.Count <> 1 Then
HCP = CVErr(xlErrValue)
Exit Function
End If
For i = 1 To Rng1.Rows.Count
retVal = retVal & "[" & Rng1.Cells(i, 1) & "," & Rng2.Cells(i, 1) & "],"
Next i
'remove last comma
If retVal <> "" Then retVal = Left(retVal, Len(retVal) - 1)
HCP = "[" & retVal & "]"
End Function