我想使用我之前在程序中计算的二进制数和频率数组来构建直方图:
Sub createHistogram(binsArray() As Variant, frequencesArray() As Variant, _
resultWorkbook As Workbook)
With resultWorkbook("result_values")
.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=frequencesArray 'error here
ActiveChart.Axes(xlCategory).Select
ActiveChart.FullSeriesCollection(1).XValues = binsArray
End With
End Sub
getFrequencesArray
功能:
Function getFrequencesArray(binsArray() As Variant, dataArray() As Double)
Dim binsNumber As Long
binsNumber = UBound(binsArray) - LBound(binsArray) + 1
Dim resultArray() As Variant
ReDim resultArray(1 To binsNumber)
resultArray(1) = 1
...
getFrequencesArray = resultArray
End Function
getBinsArray
功能:
Function getBinsArray(dataArray() As Double)
Dim binsNumber As Long
Dim binSize As Double
binsNumber = Round(VBA.Sqr(UBound(dataArray) - LBound(dataArray) + 1) + 0.5)
MsgBox ("binsNumber: " & binsNumber)
binSize = (getMaxValue(dataArray) - getMinValue(dataArray)) / (binsNumber - 1)
Dim resultArray() As Variant
ReDim resultArray(1 To binsNumber) As Variant
...
getBinsArray = resultArray
End Function
但是当我将type mismatch
指定为直方图的来源时,我收到frequencesArray
错误。如何解决该错误并从我的阵列创建直方图?
修改:
createHistogram
来自StartDataCollect
:
Sub StartDataCollect()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim globals As Object
Set globals = getGlobalVariables()
Dim dataWorkbook As Workbook
Set dataWorkbook =
ExcelApp.Application.Workbooks.Open(globals("DATA_WORKBOOK_PATH"))
Dim clientsColl() As Client
clientsColl = getClients(dataWorkbook, calculation_version)
dataWorkbook.Close
Set dataWorkbook = Nothing
Dim resultWorkbook As Workbook
Set resultWorkbook =
ExcelApp.Application.Workbooks.Open(globals("RESULT_WORKBOOK_PATH"))
Call clearAll(resultWorkbook)
'using data to create results for displaying
...
Dim binsArray() As Variant
binsArray = getBinsArray(sumLossesColl)
Dim frequencesArray() As Variant
frequencesArray = getFrequencesArray(binsArray, sumLossesColl)
Call createHistogram(binsArray, frequencesArray, resultWorkbook)
...
resultWorkbook.Save
resultWorkbook.Close
Set resultWorkbook = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.StatusBar = False
ExcelApp.Quit
End Sub
EDIT2 :
将代码更改为@ user2731076建议:
Sub createHistogram(binsArray() As Variant, frequencesArray() As Variant, _
resultWorkbook As Workbook)
With resultWorkbook.Worksheets("result_values")
.Shapes.AddChart2(201, xlColumnClustered).Select
'ActiveChart.SetSourceData Source:=frequencesArray
ActiveChart.Axes(xlCategory).Select 'error here
ActiveChart.FullSeriesCollection(1).Values = frequencesArray
ActiveChart.FullSeriesCollection(1).XValues = binsArray
End With
End Sub
但是出现Object variable or With block variable not set
错误。
答案 0 :(得分:0)
从SetSourceData方法的MSDN help page开始,源必须是范围而不是值数组。相反,我建议使用
设置Y值ActiveChart.FullSeriesCollection(1).Values = frequencesArray