【问题标题】:VBA Script to Fill Blank Cells Within an Excel Column with the Average of Nonblank Cells within that Same ColumnVBA脚本用同一列中非空白单元格的平均值填充Excel列中的空白单元格
【发布时间】:2021-06-09 00:29:41
【问题描述】:

我没有使用 VBA 的经验,希望得到一些帮助。正如标题所示,我正在寻找一个脚本,它用同一范围内所有非空白单元格的平均值填充 G 列中一定数量的空白单元格(例如,用所有非空白单元格的平均值填充 G16:G59 中的所有空白单元格G16:G59 内的单元格)。

为了让事情变得更复杂,我需要稍微动态地改变范围,因为我不确定我需要将此脚本应用到多少行以及将使用此脚本的同事可能也没有任何使用 VBA 的经验...我能想到的最简单的解决方案是让另一个单元格包含范围中最后一行的名称,或者类似这样:“用 G16:Gx 中的所有空白单元格填充G16:Gx 中所有非空白单元格的平均值,其中 x = 单元格 G12 中列出的行名"。在 G12 中,我会有一个文本说明最后一行来定义范围,例如单元格 G12 包含文本“G80”,这使得脚本内的范围为 G16:G80。

我知道我的要求很多,所以如果您能在第一时间提供指导,我将不胜感激!提前感谢您的宝贵时间。

【问题讨论】:

  • G 列的最后一个单元格是否可能为空白?如果是这样,是否有另一列可用于确定数据集的最后一行?

标签: excel vba


【解决方案1】:

我想我们都记得我们刚开始使用 VBA 编码时的情景——这就是我在这里为您提供帮助的原因。通常,您很幸运能够在您的问题上获得任何帮助,而无需提供至少一些代码和说明它没有按照您的意愿行事。使用Record Macro 按钮始终是一个不错的起点。

这里的假设是数据在您文件的“Sheet1”上,并且在您感兴趣的范围内的 G 列的最后一个单元格中有一个值。如果不是这种情况,让我知道,我将展示另一种查找最后一行的方法。

我添加了关于每种情况下(大多数)代码作用的描述,以帮助您了解正在发生的事情。让我知道你是怎么做的。

Option Explicit     '<~~ get in the habit of putting this at the top of your code
Sub FillInBlanks()

Dim ws As Worksheet '<~~ declare all variables
Dim LastRow As Long '<~~ use Long not Integer
Dim cel As Range    '<~~ use intuitive variable names
Dim avg As Double   '<~~ Double used here if you want decimal places in the average

Set ws = Sheets("Sheet1")   '<~~ be explicit with sheet references

'Best practice to determine last used row in column
LastRow = ws.Cells(Rows.Count, "G").End(xlUp).Row   '<~~ finds the last used row in column G

'Calculate the average & assign it to the variable "avg"
avg = Application.Average(ws.Range("G16:G" & LastRow))

'Loop through each cell in the defined range - one at a time
For Each cel In ws.Range("G16:G" & LastRow)
    If cel = "" Then  '<~~ = If the cell is blank, then...
        cel = avg     '<~~ ...put the average value (avg) in the cell
        cel.Font.Color = RGB(51, 102, 0) '<~~ change color to suit
    End If
Next cel      '<~~ go to the next cell in the range

End Sub

【讨论】:

  • 嗨 kevin9999,非常感谢您的描述性和详细的回复。该解决方案完美运行!最后一个问题,我将如何更改应用了“avg”变量的单元格的字体颜色?我一直在尝试使用“Application.Average”公式添加“.ThemeColor = xlThemeColorAccent6”,但我正在努力使其发挥作用
  • 深绿色很好,但实际上我更感兴趣的是理解我用来让它工作的语法。再次感谢您!
  • 完成!请注意添加代码行cel.Font.Color = RGB(51,102,0)。您可以调整 RGB 颜色以获得您想要的确切色调。