2014-11-14 27 views
0

我已經發現自己陷入了一個看起來非常簡單和愚蠢的問題,但是現在我一直在努力解決這個問題超過24小時。VBA中的總變量

我有一個字符串(由|分隔的一串數字),我想要轉換成數組,然後根據大小寫求和一些數組鍵。

我發現的第一個問題是整數長度限制,我無法相信VBA無法返回高於32767的數字(然後我發現了很多...)。在「求解」之後,我發現當試圖求和一些0值時,它實際上增加了我的總和,我找不到任何解釋。

下面你可以看到我現在有:

Public Function calcTime(TimeType As String) 
Dim jsSting As String 
Dim strSplit As Variant 
Dim tempTime as Double 

jsSting = "100|0|10080|400|0|4320|70|0|1440|30|0|2280|10|0|7400|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|300|0|15855|90|0|1721" 
'Split the string by delimiter 
strSplit = Split(jsSting, "|") 


Select Case UCase(TimeType) 
    Case "TOTAL" 
     tempTime = WorksheetFunction.Sum(strSplit(2), strSplit(5), strSplit(8), strSplit(11), strSplit(14), strSplit(17), strSplit(20), strSplit(23), strSplit(26), strSplit(29), strSplit(32), strSplit(35), strSplit(38)) 
    Case "GROUP1" ' Team 1 + Team2 
     tempTime = WorksheetFunction.Sum(strSplit(2), strSplit(5), strSplit(8), strSplit(11), strSplit(14)) 
    Case "GROUP2" ' Team 1 + Team2 + Team3 
     tempTime = WorksheetFunction.Sum(strSplit(2), strSplit(5), strSplit(8), strSplit(11), strSplit(14), strSplit(38)) 
    Case "GROUP3" ' Team 5 
     tempTime = WorksheetFunction.Sum(strSplit(17), strSplit(20), strSplit(23), strSplit(26)) 
    Case "GROUP4" ' Team 2 
     tempTime = strSplit(14) 
    Case "GROUP5" ' Team 6 
     tempTime = WorksheetFunction.Sum(strSplit(29), strSplit(32), strSplit(35)) 
End Select 

Return tempTime 
End Function 

在這個例子中,我曾嘗試使用Excel的SUM函數,以獲得期望的結果,但它並不成功。

堅持TOTAL情況。它總結如下鍵 - 值:

jsString(2) - 10080 
jsString(5) - 4320 
jsString(8) - 1440 
jsString(11) - 2280 
jsString(14) - 7400 
jsString(17) - 0 
jsString(20) - 0 
jsString(23) - 0 
jsString(26) - 0 
jsString(29) - 0 
jsString(32) - 0 
jsString(35) - 15855 
jsString(38) - 0 

這給出了一個總的41375,但是,當我做總和VBA我得到43096,我不明白爲什麼。如果我從SUM中刪除0值,它將返回正確的41k值。

希望這是有道理的,答案很簡單(我認真考慮在分配數據類型時錯過了一些東西)。

非常感謝您的幫助!

+0

我想在你的選擇的情況下,你的意思是寫'strSplit'而不是'JsSting',但是這不是我已經意識到這個問題後。 –

+0

對不起,我修好了。生成的類型,因爲我已經替換了變量名稱(內部問題) – user3352559

回答

0

你也許是指...?

Select Case UCase(TimeType) 
Case "TOTAL" 
    tempTime = WorksheetFunction.Sum(strSplit(2), strSplit(5), strSplit(8), strSplit(11), strSplit(14), strSplit(17), strSplit(20), strSplit(23), strSplit(26), strSplit(29), strSplit(32), strSplit(35), strSplit(38) 

無論如何,問題是,你還總結strSplit(38)這是1721即使您的樣品等於0,正好Excel和VBA之間的區別在寫;)

與檢查您的代碼中有一個MsgBox strSplit(38)

+0

現在感覺很愚蠢。我做了一個DEBUG MSGBOX,它總結了所有內容,並使用了38個38.非常感謝! – user3352559

+0

我敢打賭,每個開發者都至少花了一週的時間在這樣的錯誤上,不要擔心;) –

0

strsplit(38)= 1721,這是43096和41375的區別

+0

這不能解答這個問題。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 – user35443

+0

我不同意。他問爲什麼他的VBA代碼和Excel中的添加有所不同。他認爲jsString(38)是0,而它實際上是1721,這正好等於所述差異。 – Bart

+0

......所有這些都可以發表評論。 – user35443