vba 如何在范围内的每个单元格上运行公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27387155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:27:44  来源:igfitidea点击:

How to run a formula on each cell in a range

excelvbaexcel-vbaexcel-formula

提问by acr

I am looking for a excel VBA which will go through a specific range (A1 to C5)and if Bcolumn is zero, copy Ccolumn data into D

我正在寻找一个 excel VBA,它将通过特定范围(A1 to C5),如果B列为零,则将C列数据复制到D

enter image description here

在此处输入图片说明

Dont hav much experience with excel VBA, I have tried the code (which created with help of formula), but no luck.

对excel VBA没有太多经验,我尝试过代码(在公式的帮助下创建),但没有运气。

Sub Macro1()
'
' Macro1 Macro

Dim FLrange As Range
Set FLrange = Range("A1:C5")

For Each FLrange In ActiveWindow.RangeSelection

If FLrange.Value = 0 Then D$ = C$

Next FLrange

End Sub

can someone correct if it is wrong

如果错误,有人可以纠正吗

回答by Portland Runner

I agree with @tigeravatar about the formula option but if you really want VBA start with this:

我同意@tigeravatar 关于公式选项的看法,但如果您真的想要 VBA,请从以下开始:

Sub Macro1()
    Dim FLrange As Range
    Set FLrange = Range("B2:B5")

    For Each cell In FLrange
        If cell.Value = 0 Then cell.Offset(0, 2) = cell.Offset(0, 1)
    Next cell
End Sub

回答by Salvatore Fanale

this code will do exactly what you asked for:

此代码将完全满足您的要求:

Sub myMacro()
Dim myRange As Range
Set myRange = Range("B2:B5")

For Each cell In myRange
    If Range(cell.Address).value = 0 Then
        Range(cell.Offset(0, 2).Address).value = Range(cell.Offset(0, 1).Address).value
    End If
Next

End Sub

However what you have requested is easily possible simply using an equation. I am assuming you are looking for a grander VBA solution and you only provided a sample of your end goal for simplicities sake. If NOT, why not just use if/than functions in the cell...

然而,您所要求的内容只需使用一个等式即可轻松实现。我假设您正在寻找更宏大的 VBA 解决方案,并且为了简单起见,您仅提供了最终目标的示例。如果不是,为什么不在单元格中使用 if/than 函数......