簡體   English   中英

Excel VBA - 從單元格讀取時,代碼將十進制轉換為整數

[英]Excel VBA - Code is converting a decimal to integer when read from cell

我以前從未注意到這一點,我不確定是什么原因造成的。 我在 A 列中有一系列十進制值:

在此處輸入圖片說明

...以及一段應該讀取這些值的代碼:

currentValue = ActiveWorkbook.Sheets("Values").Cells(n, 1))

currentValue在變量資源管理器中被列為“Long”,但當代碼到達該行時,它存儲從 Values 工作表讀取的值,四舍五入為最接近的整數。 任何想法為什么? 它與第一個值為“0”無關,我檢查過!

我完全不知道為什么要將 long 轉換為 Int; 未定義的變體應保持其內容的格式。

在從工作表中提取 val 后,您能否單步執行代碼並查看 CurrentValue 中的值是多少? 就像...在您問題中的那一行之后, debug.Print CurrentValues 以查看它包含的內容。 我最好的猜測是,無論您最終將 CurrentValues 粘貼到何處,都將被格式化為 Int 或四舍五入到最接近的整數。

您可以在早期綁定中將 CurrentValue 聲明為 Double 或使用 CDec 函數將單元格值轉換為十進制。 在下面查看我的代碼的結果:

Public Function TestingThis()
    Dim ws     As Worksheet
    Dim dblVal As Double
    
    Set ws = Application.ThisWorkbook.Worksheets(1)
    
    For i = 2 To 8
        currentValue = ws.Cells(i, 1) 'How you have it in yor example code
        ws.Cells(i, 2) = currentValue
        
        dblVal = ws.Cells(i, 1) 'Using a early binding Double Var to retain decimal format
        ws.Cells(i, 3) = dblVal
        
        ws.Cells(i, 4) = CDec(ws.Cells(i, 1)) 'Using the CDec Function to retain decimal format
    Next i
    
End Function

顯示 Excel 和 VBA 中不同轉換技術的圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM