简体   繁体   中英

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

I have never noticed this before and I'm not sure what it causing it. I have a series of decimal values in column A:

在此处输入图片说明

...and a piece of code that is supposed to read those values:

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

currentValue is listed as a 'Long' in the variable explorer, but when the code reaches that line it stores the values read from the Values worksheet rounded to the nearest integer. Any ideas why? It has nothing to do with the first value being '0', I checked that!

I haven't the slightest idea why it's converting the long to an Int; an undefined variant should keep the format of its contents.

Can you step through your code and see what the value in CurrentValue is after pulling in the val from your worksheet? Like... right after that line in your question is, debug.Print CurrentValues to see what it contains. My best guess is that that wherever you eventually paste CurrentValues into is formatted to be Int or rounded to the nearest whole number.

You could either declare CurrentValue as a Double in early binding or convert the cell value to decimal using the CDec function. See my code's results below:

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 中不同转换技术的图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM