【问题标题】:Selecting specific row based on column value and inserting a formula根据列值选择特定行并插入公式
【发布时间】:2018-07-17 23:21:04
【问题描述】:

在包含我的数据的附加图片中,我正在尝试执行以下操作:

1) 如果 C 列中的值 = "DOSH"
,则从 I 列到末尾(BQ 列)选择所有行和单个单元格 2)一旦我为每个单元格选择了那些单元格(I 到 BQ),我想使用一个公式 "=R(-2)C/R(-3)C"

我从以下代码开始,但它选择了整行,而不仅仅是 I 到 BQ 的列。我也不确定我应该在哪里包含公式。

Sub SelRows()
Dim ocell As Range
Dim rng As Range

For Each ocell In Range("C:BQ")

If ocell.Value = "DOSH" Then

If rng Is Nothing Then

Set rng = ocell.Select
Else
Set rng = Union(rng, ocell.EntireRow)
End If
End If
Next

If Not rng Is Nothing Then rng.Select

Set rng = Nothing
Set ocell = Nothing
End Sub

【问题讨论】:

  • 尝试使用Set rng = Range("I" & ocell.row)代替Set rng = ocell.SelectSet rng = Union(rng, Range("I" & ocell.Row))代替Set rng = Union(rng, ocell.EntireRow)

标签: vba excel


【解决方案1】:

你可以试试这个吗?我不确定你的公式,所以可能需要调整。假设您的数据从第 2 行开始。

Sub SelRows()

Dim ocell As Range
Dim rng As Range

For Each ocell In Range("C2", Range("C" & Rows.Count).End(xlUp))
    If ocell.Value = "DOSH" Then
        If rng Is Nothing Then
            Set rng = Range(Cells(ocell.Row, "I"), Cells(ocell.Row, "BQ"))
        Else
            Set rng = Union(rng, Range(Cells(ocell.Row, "I"), Cells(ocell.Row, "BQ")))
        End If
    End If
Next

If Not rng Is Nothing Then
    rng.FormulaR1C1 = ""=iferror(R[-2]C/R[-3]C,"""")""
End If

Set rng = Nothing
Set ocell = Nothing

End Sub

【讨论】:

  • 效果很好。我唯一的问题是如何避免除法错误,因为我的 R[-3]C 值为零。我可以在错误转到 0 时执行吗?
  • 您可以使用 IFERROR - 在上面进行了修改。如果错误结果,这将返回一个空白,但可以更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多