首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从单元格读取负值

从单元格读取负值
EN

Stack Overflow用户
提问于 2011-08-25 21:47:06
回答 2查看 108关注 0票数 0

问题是..。当ActiveSheet.Cells(14,5).Value类似于-1.3时,我的代码失败...是什么导致了这种情况?

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-26 00:45:48

正如JMax所说,对Boon使用Double而不是Integer。我真的想给你两个建议,因为你的代码长度是它的2倍:

首先,不要使用else语句。只需声明testcell为0,并执行if -then测试,看看是否可以将其更改为1。

其次,如果您只使用一个单元格2次,那么将其存储为变量没有什么特别的好处(相反,您会失去可读性)。只需使用"cells(15,5).value",等等。你也不应该指定激活表--默认情况下它使用激活表。

从长远来看,这两个技巧应该会对你有所帮助,这是一个很好的实践。

更新

请允许我介绍一种更快、更有效的方法来做到这一点。在5个单元格范围内传递它。这样做,您只需将公式一直拖到列中,它将适用于每个单元格。

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

=测试单元(E14:I14)

代码语言:javascript
复制
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个单元格的范围被转换成一个变量数组(它可以容纳整数,字符串,双精度数,等等)。检查是使用varray完成的,因为它非常快,高效,而且你不需要担心数据类型(主要的好处之一是能够将整个范围转储到vArray中,就像我在我的代码中看到的那样)。由于我们将结果设置为0,因此不需要任何else语句,您只需执行if-thens来查看该值是否可以更改为1。

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

票数 3
EN

Stack Overflow用户

发布于 2011-08-25 22:15:13

您的Boon已声明为Integer>> http://msdn.microsoft.com/fr-fr/library/06bkb8w2(v=vs.80).aspx

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

如果你想让它工作,你需要使用Double

代码语言:javascript
复制
Function TestCell() As Integer
    Dim Boon As Double
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7191502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档