VBA功能不是指正确的表格

时间:2014-03-18 16:23:59

标签: excel function vba excel-vba

我在VBA中为另一个程序中的图表输出制作数据解析器。我制作了这个vba代码并没有提到正确的范围。

这是功能:

Function HCAlt(Rng1 As Range, Rng2 As Range, Rng3 As Range, Rng4 As Range) As String
' this function will take columns of data and properly format them for highcharts scatter pairs
Dim retVal As String
Dim i As Integer
Dim startRow As Integer
startRow = Rng1.Row

'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 Or Rng3.Rows.count <> Rng2.Rows.count Then
    HCAlt = CVErr(xlErrValue)
    Exit Function
End If

For i = 0 To Rng1.Rows.count - 1
    retVal = retVal & "{x:" & Rng3.Cells(startRow + i, 1) & ",y:" & Rng4.Cells(startRow + i, 1) & ",samp:'" & Rng1.Cells(startRow + i, 1) & "'" & ",Rock:'" & Rng2.Cells(startRow + i, 1) & "'},"
Next i
'remove last comma
If retVal <> "" Then retVal = Left(retVal, Len(retVal) - 1)

HCAlt = "[" & retVal & "]"
End Function

调用该函数的单元格是以下代码:

 HCAlt(INDIRECT(M$47),INDIRECT(M46),INDIRECT(M65),INDIRECT(M61))

它所指的细胞是范围:

 Cell M46= PlotData!R55:R141  'this is a range on sheet "PlotData"
 Cell M47= PlotData!A55:A141  'this is a range on sheet "PlotData"
 Cell M61= StData!L55:L141    'this is a range on sheet "StData"
 Cell M65= StData!P55:P141    'this is a range on sheet "StData"

功能&#34;工作&#34;但它并不是指我想要它的细胞(它给我回垃圾数据)。

我是否需要声明它所指的表格?或者是间接端口的范围值,告诉函数找到哪个工作表?

由于

1 个答案:

答案 0 :(得分:0)

这是我的问题。我以为我需要在范围开始的行上“开始”。在我的例子中它是55,所以我创建了一个变量来获取该行,然后将其添加到单元格行。

Dim startRow As Integer
startRow = Rng1.Row

Rng3.Cells(startRow + i, 1) '  this is part of the code where I added this starting row- see above'

我删除了起始行变量并改为使用它:

Rng3.Cells(i, 1)

由于我的数据是指对不同排序的相同数据的“重复”表格,我可以更改我所指的单元格,因此它们都在同一张纸上。

Cell M46= StData!R55:R141  'this is a range on sheet "StData"
Cell M47= StData!A55:A141  'this is a range on sheet "StData"
Cell M61= StData!L55:L141  'this is a range on sheet "StData"
Cell M65= StData!P55:P141  'this is a range on sheet "StData"

这符合正确的价值观。我不确定最后一部分是否有任何区别,但我正在安全地玩它。