英文:
Excel VBA If Statement
问题
在单元格A1中,我有0.04,这是大于0的。但在B1中,我没有返回“pass”。
英文:
Sub test()
Dim score As Integer, result As String
score = Range("A1").Value
If score > 0 Then result = "pass"
Range("b1").Value = result
End Sub
I'm missing something here. In cell A1 i have 0.04 which is > 0
But in B1 I'm not returning pass
答案1
得分: 1
如果你是VBA新手,可能更好地引用单元格及其.Value
属性,该属性是一个Variant
,设计用于更直观地处理多种类型的值:
Sub test()
Dim score As Range: Set score = Range("A1")
Dim result As Range: Set result = Range("B1")
If 0 < score.Value Then
result.Value = "通过"
' Else
' result.Value = "不通过"
End If
End Sub
英文:
If you are new to VBA, it may be better to reference cells and their .Value
property, which is a Variant
, and is designed to handle values of multiple types more intuitively:
Sub test()
Dim score As Range: Set score = Range("A1")
Dim result As Range: Set result = Range("B1")
If 0 < score.Value Then
result.Value = "pass"
' Else
' result.Value = "fail"
End If
End Sub
答案2
得分: 1
Populate Conditionally
- 您选择了错误的数据类型,正如我在您的评论中提到的那样,
Score
的数据类型。 - 您应该对整数使用 Long 数据类型(参见这篇传奇帖子以了解为什么不使用 Integer),对小数使用 Double 数据类型。
- 要了解更多有关数据类型的信息,请阅读文档。
Sub PopulateConditionally()
Dim ws As Worksheet: Set ws = ActiveSheet ' 改进!
' 可能是任何类型(数字、字符串、布尔值、错误),因此使用“Variant”类型。
Dim CellValue As Variant: CellValue = ws.Range("A1").Value
Dim Score As Double, Result As String
If VarType(CellValue) = vbDouble Then ' 是一个数字
Score = CDbl(CellValue) ' 显式转换(您掌控着)
' 或:
' Score = CellValue ' 隐式转换(VBA掌控着)
If Score > 0 Then
Result = "pass"
' 否则 <=0; 什么也不做; “Result”保持为空字符串("")
End If
' 否则 不是数字; 什么也不做; “Result”保持为空字符串("")
End If
ws.Range("B1").Value = Result
End Sub
英文:
Populate Conditionally
- You have chosen the wrong data type for
Score
as I mentioned in your comments. - You want to use the Long data type for whole numbers (see this legendary post why not Integer) and the Double data type for decimal numbers.
- For more information on data types, read through the documentation.
<!-- language: lang-vb -->
Sub PopulateConditionally()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
' Could be anything (number, string, boolean, error) so use a 'Variant' type.
Dim CellValue As Variant: CellValue = ws.Range("A1").Value
Dim Score As Double, Result As String
If VarType(CellValue) = vbDouble Then ' is a number
Score = CDbl(CellValue) ' explicit conversion (you're in control)
'Or:
'Score = CellValue ' implicit conversion (VBA is in control)
If Score > 0 Then
Result = "pass"
'Else ' <=0; do nothing; 'Result' remains an empty string ("")
End If
'Else ' is not a number; do nothing; 'Result' remains an empty string ("")
End If
ws.Range("B1").Value = Result
End Sub
答案3
得分: 0
你需要将这行代码中的 "Dim score As Integer" 更改为 variant 或 double 数据类型。因为它的整数值 0.04 会以 0 的形式存储在变量中。
英文:
For this line "Dim score As Integer" you will have to change data type to variant or double. As its integer 0.04 will be stored as 0 in the variable
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论