我有一个电子表格,其中包含x和y列下的数据。有一些y值缺失,我需要制作一个使用x值的脚本文件,并使用线性方程计算缺失的y值。
此外,y列中有部分包含数据,然后缺少数据,然后是数据等。是否还有一种方法可以在除了单元格之外的所有单元格中使用该等式那里已经有了价值。
如果需要,我可以提供示例工作簿。任何帮助将不胜感激。
谢谢,
编辑: 我发布了我尝试过的链接。我是Excel的新手,所以这可能不是最好的尝试。
Sub LinearCorrelation()
Dim Data As Integer
Dim Result As Integer
Data = ActiveSheet.Range("B2").Select
Result = 2 * Data + 12.5
Sheets("Sheet3").Range("D2").Value = Result
End Sub
当我运行上面的脚本时。我在D2中得到-1这是错误的。 '数据'的值是10,所以答案应该是32.5。
答案 0 :(得分:0)
您的代码中存在相当多的问题,因此我将尝试通过示例解决它们。请参阅下面的内联评论
Sub LinearCorrelation()
Dim xRange As Range
Dim yRange As Range
Dim xData As Variant
Dim yData As Variant
Dim i As Long
' for ease of updating later
Const Slope = 2#
Const Intercept = 12.5
With Worksheets("Sheet3") '<-- lets assume all data is on this sheet
Set xRange = .Range("A1") '<-- adjust to suit the location of your x data. Use a single cell at the top of your data.
Set yRange = .Range("B1") '<-- adjust to suit the location of your y data. Use a single cell at the top of your data.
' expand range to include all x data rows
Set xRange = .Range(xRange, .Cells(.Rows.Count, xRange.Column).End(xlUp))
Set yRange = yRange.Resize(xRange.Rows.Count, 1)
' move ranges to variant arrays for speed
xData = xRange.Value2
yData = yRange.Value2
For i = 1 To UBound(xData, 1)
' only calculate missing y values
If IsEmpty(yData(i, 1)) Then
yData(i, 1) = Slope * xData(i, 1) + Intercept
End If
Next i
' return data to y range
yRange = yData
End With
End Sub