所以我有一个单元格(A2),其中包含一个Integer值(5)。我想要一个查看单元格的switch语句,然后如果该单元格的值大于50000做某事,如果该值小于50000就做某事。
这是我的代码不起作用,代码行threshold = 50000
说“溢出”:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Dim state As Integer
Dim threshold As Integer
threshold = 50000
state = Sheet1.Range("A2").Value
Select Case state
Case state < threshold
'Do something
Debug.Print (state)
Case Is >= threshold
'Do something
Debug.Print (state)
End Select
End Sub
我该如何解决这个问题?
答案 0 :(得分:4)
问题在于:
Sheet1.Range.Value("$A$2")
使用Select Case
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim state As Integer
state = CInt(Sheet1.Range("$A$2"))
Select Case state
Case Is > Target.Value
Debug.Print "less than " & state
Case Is < Target.Value
Debug.Print "greater than " & state
Case Else
Debug.Print "Equals"
End Select
End Sub
使用if
声明
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim state As Integer
state = CInt(Sheet1.Range("$A$2"))
If Target.Value < state Then
Debug.Print "less than " & state
ElseIf Target.Value > state Then
Debug.Print "greater than " & state
Else
Debug.Print "Equals"
End If
End Sub
<强> POST_EDIT:强>
对于Integer
数据类型,50000太大,因此请将其标注为Long
数据类型,以避免溢出
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim threshold As Long
threshold = 50000
Select Case Target.Value
Case Is >= threshold
Debug.Print "greater or equal " & threshold
Case Is < Target.Value
Debug.Print "smaller than " & threshold
Case Else
Debug.Print "Can't calculate! Error"
End Select
End Sub
答案 1 :(得分:2)
您的Range语句错误
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Dim state As Integer
state = Sheet1.Range("A2").Value
Select Case state
Case Is < 5
'Do something
Debug.Print (state)
Case Is > 5
'Do something
End Select
End Sub
如果州= 5,你没有提到要做什么?