我對 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 等等。
我知道解決方案可能非常明顯,但我似乎無法弄清楚如何去做。
感謝您提供的任何幫助!
uj5u.com熱心網友回復:
你可以
- 基于簡單的 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
uj5u.com熱心網友回復:
簡化多個If陳述句
微軟檔案
Creating Object VariablesConst statementFor Each...Next statementRange.Resize propertyRange.EntireRow propertyIsNumeric 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343894.html
