将等式应用于列
Applying equation to column
我有一个电子表格,其中包含 x 和 y 列下的数据。缺少一些 y 值,我需要制作一个使用 x 值并使用线性方程计算缺失的 y 值的脚本文件。
此外,y 列中的某些部分有数据,然后它缺少数据,然后有数据等。是否还有一种方法可以在一个范围内的所有单元格上使用方程式,但其中的单元格除外已经是 y 值了。
如果需要,我可以提供示例工作簿。任何帮助将不胜感激。
谢谢,
编辑:
我已经发布了我尝试过的 link。我是 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,这是错误的。 'Data' 的值为 10,因此答案应为 32.5。
您的代码中存在不少问题,因此我将尝试通过示例解决这些问题。请参阅下面的内联评论
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
我有一个电子表格,其中包含 x 和 y 列下的数据。缺少一些 y 值,我需要制作一个使用 x 值并使用线性方程计算缺失的 y 值的脚本文件。
此外,y 列中的某些部分有数据,然后它缺少数据,然后有数据等。是否还有一种方法可以在一个范围内的所有单元格上使用方程式,但其中的单元格除外已经是 y 值了。
如果需要,我可以提供示例工作簿。任何帮助将不胜感激。
谢谢,
编辑: 我已经发布了我尝试过的 link。我是 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,这是错误的。 'Data' 的值为 10,因此答案应为 32.5。
您的代码中存在不少问题,因此我将尝试通过示例解决这些问题。请参阅下面的内联评论
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