[英]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 重復,依此類推。
我知道解決方案可能非常明顯,但我似乎無法弄清楚如何去做。
感謝您提供的任何幫助!
你可以
=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
語句微軟文檔
Creating Object Variables
Const statement
For Each...Next statement
Range.Resize property
Range.EntireRow property
IsNumeric function
編碼
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.