创建数据系列线性趋势以填充同一列中的单元格之间

时间:2019-10-18 00:29:54

标签: excel vba find range

我目前正在使用修改后的数据收集,每个记录值中都有空白。我想使用“主页”选项卡下的Excel填充工具(editing(group)-> fill-> series。Rows,linear,trend)来生成具有线性趋势的值。我正在使用A2:A6569的范围,因此手动执行此操作不切实际。我已经使用Excel函数if语句生成了此数据,如果未调用值,则将其放置在每个单元格中。我找到并尝试的所有内容均无法正常工作。

数据样本:(其中x是空白单元格)

  1. “标题”
  2. 0.004
  3. x
  4. x
  5. x
  6. 5.214
  7. x
  8. x
  9. 7.01
  10. x
  11. x
  12. x
  13. 6.97

我尝试过的伪代码:

    Dim rStoA, rStoB, rStoC As Range
    With ActiveSheet.Range("A2:A6569")
        for each value in range 
            if IsNumeric(value) And IsEmpty(rStoA) Then
                rStoA = value
            else if IsNumeric(value) and IsNumeric(rStoA) Then
                rStoB = value
                Set rStoC = .Range(rStoA, rStoB)
                rStoC.DataSeries Rowcol:=xlColumns, Type:=xlLinear, 
                  Date:=xlDay, Trend:=True
                rStoA = rStoB
            end if
        next
    End With 

通过记录宏,我从Excel的填充实用程序中找到了所需的功能:

"selected_range".DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, Trend:=True

我相信我的问题是我使用Range,但是我被困住了。

此外,如果我使用Range.Find会更好吗?如果是这样,有人可以以此引导我朝正确的方向发展吗?

我感谢任何建议。 谢谢!

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您想做的事情,则可以执行以下操作:

Option Explicit

Sub fillSeries()
Dim sht As Worksheet
Dim firstCell As Range, lastCell As Range
Dim fillRange As Range, cell As Range
Dim lastRow As Long, firstRow As Long
Dim fillCol As String
Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
lastRow = 13 'the row of the last cell you want to fill
firstRow = 2 'the row where your data begins
fillCol = "A" 'the column to be filled

For Each cell In Range(sht.Cells(firstRow, fillCol), sht.Cells(lastRow, fillCol))
    If cell.Value = "" Then
        cell.ClearContents
    End If
Next cell
Set firstCell = sht.Range(fillCol & firstRow)
While firstCell.Row <> lastRow
    If firstCell.End(xlDown).Row > lastRow Then
        Set lastCell = sht.Range(fillCol & lastRow)
    Else
        Set lastCell = firstCell.End(xlDown)
    End If
    sht.Range(firstCell, lastCell).DataSeries Type:=xlLinear, Trend:=True
    Set firstCell = lastCell
Wend

End Sub

基本上,该代码查找成对的非空白单元格,它们之间用空白单元格隔开,并填充它们之间的空白。先前使用的对中的最后一个单元格成为下一个单元格中的第一个,依此类推,直到到达最后一个单元格为止。

我不确定范围的最后一个单元格是否已满,所以我以某种方式构建了代码,以便您可以手动定义哪个单元格是最后一个单元格。

因此,对于您提供的数据示例,假设填充应在第13行(其中6,97是)停止,结果如下:

enter image description here

如果您想继续填充直到说第20行,结果将是:

enter image description here