2017-03-01 183 views
0

我試圖通過簡單地總結A/B和B/C的外匯匯率並乘以找到A/C匯率的方法來計算交叉匯率,並且我一直得到0 。這是代碼:Excel VBA不斷返回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

您可以使用Average()功能:

Function forex(audData As Range, euData As Range) 
    With WorksheetFunction 
     forex = .Average(audData) * .Average(euData) 
    End With 
End Function 
+2

這比OP想要做的更短更快,儘管他們仍然需要意識到使用未聲明的變量的危險,所以我會保留我更詳細的答案,儘管這顯然是優越的。 –

+0

@JohnColeman,我同意 – user3598756

+0

@ArenGallagher,你通過了嗎? – user3598756

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變量具有合理的默認值。

+1

我認爲OP使用循環的問題比你注意到的還要多 - 也就是說,如果audData或euData中的某些單元格爲空,那麼Count將小於單元格的數目,只會迭代第一個「a」或「e」單元(即使這可能會包含空單元格),並且會忽略該範圍內的一些最終單元格。 (它可能應該是'audData.Count'而不是'Application.Count(audData)',在循環中有一個適當的'If Not IsEmpty(..)Then')。但是+1指出'Option的優點Explicit'! – YowE3K