繁体   English   中英

有没有更简单的方法来编写这个 IF 语句?

[英]Is there an easier way to write this IF statement?

我对 VBA 非常陌生,并试图在学习过程中学习。 我 100% 确定有一种更简单的方法来压缩此代码,而不是为每个单元格和相应的单元格键入If语句。

这是我正在使用的代码:

Sub Test()
    If Range("B1").Value > 0 Then
        Range("A1").Value = 0
    End If
    
    If Range("B2").Value > 0 Then
        Range("A2").Value = 0
    End If
    
    If Range("B3").Value > 0 Then
        Range("A3").Value = 0
    End If
    
    If Range("B4").Value > 0 Then
        Range("A4").Value = 0
    End If
    
    If Range("B5").Value > 0 Then
        Range("A5").Value = 0
    End If
    
    If Range("B6").Value > 0 Then
        Range("A6").Value = 0
    End If
End Sub

图片

我使用的范围是 A1:A6 然后将它与 B1:B6 的值进行比较并说如果 B1 > 0 那么 A1 = 0,然后对 A2 和 B2 重复,依此类推。

我知道解决方案可能非常明显,但我似乎无法弄清楚如何去做。

感谢您提供的任何帮助!

你可以

  • 基于简单的 Excel 公式在 VBA 中使用公式评估
    =IF(B1:B6,A1:A6,0)

替换 A 列中的原始数据或

  • 将提到的公式直接写入例如C1受益于版本 2019+/MS 365 的更新动态功能,将其显示为所谓的溢出范围(否则您需要将其输入为数组公式,通过C trl+ S hift+ E nter 确认它)

VBA 中的示例调用

Option Explicit                         ' head of code module (force declaration of variables and objects)

Sub Example()
    Dim ws As Worksheet
    Set ws = Sheet1                     ' << change to your project's sheet Code(Name)
    Dim data As Variant                 ' provide for a 1-based 2-dim datafield array
    'assign worksheet related evaluation to data
    data = ws.Evaluate("=If(B1:B6,A1:A6,0)")
    'write to target
    ws.Range("A1").Resize(UBound(data), 1).Value = data
End Sub

简化多个If语句

微软文档

编码

  • 两个程序的作用相同。 由于使用常量,第一个解决方案可以通过在一个地方(在代码的开头)修改值来快速适应。
Option Explicit

Sub ForEachNext()
    
    Const sfCellAddress As String = "B1"
    Const srCount As Long = 6
    
    Const dCol As String = "A"
    
    Dim ws As Worksheet: Set ws = ActiveSheet
    
    Dim sCell As Range
    Dim sValue As Variant
    Dim dCell As Range
    
    For Each sCell In ws.Range(sfCellAddress).Resize(srCount).Cells
        sValue = sCell.Value
        If IsNumeric(sValue) Then ' is a number
            If sValue > 0 Then ' is greater than
                Set dCell = sCell.EntireRow.Columns(dCol)
                dCell.Value = 0
            'Else ' is less than or equal ('sValue <= 0')
            End If
        'Else ' is not a number
        End If
    Next sCell

End Sub

Sub ForEachNextMagicNumbers()
    
    Dim ws As Worksheet: Set ws = ActiveSheet
    
    Dim sCell As Range
    Dim sValue As Variant
    Dim dCell As Range
    
    For Each sCell In ws.Range("B1").Resize(6).Cells
        sValue = sCell.Value
        If IsNumeric(sValue) Then ' is a number
            If sValue > 0 Then ' is greater than
                Set dCell = sCell.EntireRow.Columns("A")
                dCell.Value = 0
            'Else ' is less than or equal ('sValue <= 0')
            End If
        'Else ' is not a number
        End If
    Next sCell

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM