我在excel中有数据,我需要填写缺失(空白)数据,输入数据如下:
row1 --> 1 2 3 blank 5 6 blank blank 9 10
row2 --> 2 4 blank blank 10 12 14 blank 18 blank
VBA代码必须读取每一行并像这样填充它们:
row1 --> 1 2 3 4 5 6 7 8 9 10
row2 --> 2 4 6 8 10 12 14 16 18 20
在VBA(excel)中有明确的解决方案吗?
答案 0 :(得分:8)
这是一个数学解的例子:
x
(在接下来的2个步骤中,我们需要将它们作为数组)m
c
y
插入缺失值y = m * x + c
示例:
Option Explicit
Public Sub LinearInterpolateRowWise()
Dim DataRange As Range
Set DataRange = Worksheets("Sheet1").Range("A1:J3")
Dim ArrX As Variant 'create an array of x-values
ReDim ArrX(1 To 1, 1 To DataRange.Columns.Count)
Dim c As Long
For c = 1 To DataRange.Columns.Count
ArrX(1, c) = c
Next c
Dim iRow As Long, iCol As Long
For iRow = 1 To DataRange.Rows.Count 'loop row wise
Dim Slope As Double
Slope = Application.WorksheetFunction.Slope(DataRange.Rows(iRow), ArrX)
Dim Intercept As Double
Intercept = Application.WorksheetFunction.Intercept(DataRange.Rows(iRow), ArrX)
For iCol = 1 To DataRange.Columns.Count 'interpolate missing values
If DataRange.Cells(iRow, iCol) = vbNullString Then
DataRange.Cells(iRow, iCol) = Slope * iCol + Intercept 'y = m * x + c
End If
Next iCol
Next iRow
End Sub
以下是第3行插值的可视化显示
:那么,发生的事情是我们通过给定的点(蓝色)计算线性方程,并用它来计算缺失点(橙色)。