从单元读取负值

问题是这样的..当ActiveSheet.Cells(14,5).Value是类似-1.3我的代码失败…是什么原因造成的?

Function TestCell() As Integer Dim Boon As Integer Dim nextBoon As Integer Dim nextTwo As Integer Dim nextOne As Integer Dim nextThree As Integer Boon = ActiveSheet.Cells(14, 5).Value nextBoon = ActiveSheet.Cells(14, 6).Value nextTwo = ActiveSheet.Cells(14, 7).Value nextOne = ActiveSheet.Cells(14, 8).Value nextThree = ActiveSheet.Cells(14, 9).Value If Boon <= 1.8 And Boon >= -1.8 Then If nextBoon <= 1000 And nextBoon >= -1000 Then If nextTwo <= 0.36 And nextTwo >= -0.36 Then If nextOne <= 0.13 And nextOne >= -0.13 Then If nextThree <= 1.2 And nextThree >= -1.2 Then TestCell = 1 Else TestCell = 0 End If Else TestCell = 0 End If Else TestCell = 0 End If Else TestCell = 0 End If Else TestCell = 0 End If End Function 

正如JMax所说的,使用Double而不是Integer作为Boon。 我真的想给你两点build议,因为你的代码长度可能是2倍:

首先,不要使用else语句。 只要声明testing单元是0,并做你的if-thens,看看你是否可以改变它为1或不。

其次,如果你只使用一个单元格2次,将它作为一个variables存储没有什么特别的好处(另一方面你会失去可读性)。 只需使用“cells(15,5).value”等等。你不应该指定activesheet – 默认情况下它使用activesheet。

从长远来看,这两个技巧应该可以帮助你,这是一个很好的练习。

更新

请允许我介绍一个更快,更有效的方法来做到这一点。 你通过它在5个单元格范围内。 这样做,你可以将公式一直拖到你的列,它将适用于每个单元格。

在你的例子中,你可以使用以下命令来调用它:

= TestCell(E14:I14)

 Function TestCell(ByVal myRange As Range) As Long Dim vArray As Variant Dim result As Long result = 0 vArray = myRange.Value If vArray(1, 1) <= 1.8 And vArray(1, 1) >= -1.8 Then If vArray(1, 2) <= 1000 And vArray(1, 2) >= -1000 Then If vArray(1, 3) <= 0.36 And vArray(1, 3) >= -0.36 Then If vArray(1, 4) <= 0.13 And vArray(1, 4) >= -0.13 Then If vArray(1, 5) <= 1.2 And vArray(1, 5) >= -1.2 Then result = 1 End If End If End If End If End If TestCell = result End Function 

它是如何工作的 :5单元格范围转换为一个变种数组(可以保存整数,string,双打等等)。 检查完成使用varray,因为它是疯狂的快速,有效的,你不需要担心数据types(主要好处之一是能够转储整个范围成vArray,你看我在我的代码)。 由于我们将结果设置为0,因此我们不需要任何其他语句,只需执行if-thens即可查看该值是否可以更改为1。

使用这种方法,计算可以在几微秒内完成,并且每次更改5个单元格中的一个时,函数会自动更新,因此您可以获得实时结果。

你的恩赐是一个Integer >> http://msdn.microsoft.com/fr-fr/library/06bkb8w2(v=vs.80).aspx

所以Boon = ActiveSheet.Cells(14, 5).Value如果ActiveSheet.Cells(14, 5).Value-1.3 ActiveSheet.Cells(14, 5).Value将返回-1

如果你想要它,你需要使用Double

 Function TestCell() As Integer Dim Boon As Double