[算表] VBA計算後溢位問題

看板Office作者 (溫柔殺手)時間5年前 (2020/07/07 10:49), 5年前編輯推噓0(0020)
留言20則, 2人參與, 5年前最新討論串1/1
軟體:Excel 版本:Office 365 各位版上的神人早上好。 我撰寫了一個簡單的用料計算程式。 執行的時候會卡在 PrPS = Round(1220 * 2440 * MP * Density * Thick / 10 ^ 6, 2) 錯誤資訊是"溢位" 我有嘗試把變數宣告為Variant或著甚至不宣告都出現這個問題 在儲存格中打公式不會有問題,但是在VBA中就會有。 在這應用情境中 MP=170, Density=2.7, Thick=2, length=133.5, width=133.5, buffer=2 煩請高手協助,感恩。 --------我是Code-------- Sub Non_circule_material_calculate(length As Single, width As Single, buffer As Single, MP As Single, Density As Single, Thick As Single) Dim R_L, R_W As Single 'R_L stands for remainder of length Dim PsPS As Integer 'PsPP stands for pice per sheet Dim PrPS As Variant 'PrPS stands for price per sheet Dim PrPP As Single 'PrPP stands for price per pice Dim CoilP As Variant 'Coil price PrPS = Round(1220 * 2440 * MP * Density * Thick / 10 ^ 6, 2) R_L = (1220 Mod (length + buffer)) * (length + buffer) R_W = (1220 Mod (width + buffer)) * (width + buffer) If R_L < R_W Then PsPP = (1220 \ (length + buffer)) * (2440 \ (width + buffer)) PrPP = PrPS / PsPS Else '除卻第一種狀況只有等於與不等於的問題。如果是等於,那麼不論是哪一種排 法其實都沒有問題。 PsPP = (2440 \ (length + buffer)) * (1220 \ (width + buffer)) PrPP = PrPS / PsPS End If CoilP = Round((length + buffer) * (width + buffer) * MP * Density * Thick / 10 ^ 6, 2) [D10] = CoilP [D11] = PrPP End Sub -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.33.116.8 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Office/M.1594090178.A.A66.html ※ 編輯: yimean (114.33.116.8 臺灣), 07/07/2020 10:50:36

07/07 11:09, 5年前 , 1F
如無合適方式的話,可改為1 / 10 ^ 6 * 1220 * 2440 * MP
07/07 11:09, 1F

07/07 11:09, 5年前 , 2F
* Density * Thick
07/07 11:09, 2F

07/07 11:16, 5年前 , 3F
或是 MP * Density * Thick * 1220 * 2440 / 10 ^ 6
07/07 11:16, 3F

07/07 11:19, 5年前 , 4F
若要以原本1220 * 2440 * MP..的話,1220改為csng(1220)
07/07 11:19, 4F

07/07 14:46, 5年前 , 5F
@s大Csng(1220)的解決方法是可行的,感謝。可是,為什麼
07/07 14:46, 5F

07/07 14:47, 5年前 , 6F
只有包一個1220就可以呢?煩請撥冗解惑,感謝。
07/07 14:47, 6F

07/07 14:59, 5年前 , 7F
出現溢位的錯誤視窗,按說明有寫
07/07 14:59, 7F

07/07 15:00, 5年前 , 8F
轉型為整數integer所以溢位
07/07 15:00, 8F

07/07 15:08, 5年前 , 9F
當然以clng也是可以,目的就是不要被轉型
07/07 15:08, 9F

07/07 15:38, 5年前 , 10F
@s大,我看了說明,說明也是只包一個,我的疑問是,為什麼
07/07 15:38, 10F

07/07 15:39, 5年前 , 11F
不是包整個算式。這跟內建函數的概念不太依樣呢。
07/07 15:39, 11F

07/07 16:03, 5年前 , 12F
說明網頁內搜尋運算子,*運算子
07/07 16:03, 12F

07/07 16:03, 5年前 , 13F
註解有寫result 的資料類型通常是運算式的相同的最精確運
07/07 16:03, 13F

07/07 16:03, 5年前 , 14F
算式。 精確的順序,從最低到最精確,是Byte、integer(整
07/07 16:03, 14F

07/07 16:03, 5年前 , 15F
數)、 Long、Single、Currency、Double....
07/07 16:03, 15F

07/07 16:03, 5年前 , 16F
1220*2440都是做為整數integer來運算,套到上述註解來看相
07/07 16:03, 16F

07/07 16:03, 5年前 , 17F
同最精確就會是以integer,那就溢位了,那改以1220*MP來看
07/07 16:03, 17F

07/07 16:03, 5年前 , 18F
,變數MP是single,最精確是single,所以不會溢位,這就是
07/07 16:03, 18F

07/07 16:03, 5年前 , 19F
為什麼只要改一個就好,要clng、csng加在1220或2440都可以
07/07 16:03, 19F

07/08 11:20, 5年前 , 20F
@s原來如此,感恩您。
07/08 11:20, 20F
文章代碼(AID): #1V0-B2fc (Office)
文章代碼(AID): #1V0-B2fc (Office)