Excel VBA不断返回0

时间:2017-03-01 23:46:20

标签: excel vba excel-vba

我试图通过简单地将A / B和B / C的外汇汇率相加并乘以找到A / C汇率的均值来计算交叉汇率,然后我一直收到0。这是代码:

Function forex(audData As Range, euData As Range)

    a = Application.Count(audData)
    e = Application.Count(euData)
    'Counts how many values are in the data

    aSum = 0
    eSum = 0
    aMean = 0
    eMean = 0

    For i = 1 To aud ' This sums the 1st forex rate and finds the mean
        aSum = aSum + audData(i)
    Next i

    aMean = aSum / a

    For i = 1 To eu ' This sums the 2nd forex rate and finds the mean
        eSum = eSum + euData(i)
    Next i

    eMean = eSum / e

    forex = (aMean * eMean)

End Function

2 个答案:

答案 0 :(得分:2)

您可以使用$scope.snPaste = function(e) { //First define the clean content var cleanUp = e.originalEvent.clipboardData.getData('text'); //Have it wait for 0.5 seconds to update the pasted setTimeout(function () { $scope.$apply(function () { $scope.post.description = cleanUp; //Here I update the model. }); }, 500); }; 功能:

Average()

答案 1 :(得分:2)

您似乎是未声明变量的受害者。你有两个循环,

For i = 1 To aud 

和(稍后)

For i = 1 To eu

其中既未声明aud也未声明eu。因此,它们默认为隐式值为0的变体,因此这些循环都不会执行,并且所有变量都保持在0

你真的应该养成在所有模块的顶部使用Option Explicit的习惯。这可以通过在VBA编辑器选项中启用选项Require Variable Declarations来自动完成。从长远来看,它将为您节省数小时的调试时间。

我无法测试您的代码,但如果您声明变量并将audeu替换为我认为您的意思,那么您将获得:

Function forex(audData As Range, euData As Range) As Double
   Dim a As Long, e As Long, aSum As Double, eSum As Double, aMean As Double, eMean As Double, i As Long
    a = Application.Count(audData)
    e = Application.Count(euData)
    'Counts how many values are in the data

    For i = 1 To a ' This sums the 1st forex rate and finds the mean
        aSum = aSum + audData(i)
    Next i

    aMean = aSum / a

    For i = 1 To e ' This sums the 2nd forex rate and finds the mean
        eSum = eSum + euData(i)
    Next i

    eMean = eSum / e

    forex = (aMean * eMean)

End Function

我跳过像aSum = 0这样的行,因为正确声明的VBA变量具有合理的默认值。