问题
I have data in excel , I need fill missing (blank) data, the input data is like:
row1 --> 1 2 3 blank 5 6 blank blank 9 10
row2 --> 2 4 blank blank 10 12 14 blank 18 blank
the VBA code must read each rows and fill them like :
row1 --> 1 2 3 4 5 6 7 8 9 10
row2 --> 2 4 6 8 10 12 14 16 18 20
is there clear solution to do this in VBA(excel)?
回答1:
Here is an Example for a mathematical solution:
- Generate x-values
x
(we need them as array for the next 2 steps) - Calculate the slope
m
for the given row values - Calculate the intercept
c
for the given row values - Interpolate the missing values
y
withy = m * x + c
Example:
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
So assuming this source data
It interpolates like this
The following is a visualization of the interpolation of row 3:
So what happens is we calculate the linear equation through the given points (blue) and use it to calculate the missing point (orange).
This will even work for non linear original points (blue) like in the following Example.
来源:https://stackoverflow.com/questions/53554615/interpolate-missing-data