首页 > 解决方案 > 单维数组在检索中自动舍入值

问题描述

该数组从电子表格中提取信息并进行乘法运算,得到一个带 2 个小数点的数字,当我进行求和或进行代码循环并将数组中的值相加时,它们会自动舍入。有任何想法吗? 从电子表格中获取的值的屏幕截图

Function DisplayWeight(ButtonType)

Dim ws As Worksheet
Dim WArray() As Double
Dim i, j, k, TotalWeight As Integer

Set ws = Sheets("BillOfLading")

j = 1
    For i = 26 To 51 'pg 1
        If ButtonType = "kg" And ws.Cells(i, 1) <> "" Then
            If j = 1 Then
                 ReDim WArray(1)
                 WArray(1) = ws.Cells(i, 1) * ws.Cells(i, 24)
                 ws.Cells(i, 27) = ws.Cells(i, 1) * ws.Cells(i, 24) & " kg"
                 j = j + 1
            Else
                ReDim Preserve WArray(j)
                    WArray(j) = ws.Cells(i, 1) * ws.Cells(i, 24)
                    ws.Cells(i, 27) = ws.Cells(i, 1) * ws.Cells(i, 24) & " kg"
                 j = j + 1

            End If
        Else
            If ButtonType = "lbs" And ws.Cells(i, 1) <> "" Then
                If j = 1 Then
                     ReDim WArray(1)
                     WArray(1) = ws.Cells(i, 1) * ws.Cells(i, 24)
                     ws.Cells(i, 27) = ws.Cells(i, 1) * ws.Cells(i, 24) * 2.20462 & " lbs"
                     j = j + 1
                Else
                    For k = UBound(WArray) To j
                        ReDim Preserve WArray(k)
                            WArray(k) = ws.Cells(i, 1) * ws.Cells(24)
                            ws.Cells(i, 27) = ws.Cells(i, 1) * ws.Cells(i, 24) * 2.020462 & " lbs"

                    Next k
                    j = j + 1
                End If
            End If
        End If
    If ButtonType = "kg" And ws.Cells(i, 1) = "" Then
        GoTo SumTotals
    End If

    Next i

SumTotals:
        TotalWeight = 0
        For i = 1 To UBound(WArray)
            TotalWeight = WorksheetFunction.Round(TotalWeight + WArray(i), 3)
            Debug.Print TotalWeight
        Next i

        If ButtonType = "kg" Then
            ws.Cells(60, 8) = TotalWeight & " kg"
        End If
        If ButtonType = "lbs" Then
            ws.Cells(60, 8) = TotalWeight & " lbs"
        End If
End Function

循环进入第一页i = 26 to 51并比较ButtonType(工作表上有两个按钮触发此功能),数学是否将产品的值放入数组中,并将其放入“总重量”列(ws.cells(i,27))中正确的描述(公斤或磅)

标签: vbaexcel

解决方案


感谢斯科特·克兰纳,

Dim TotalWeight as Double是正确答案。


推荐阅读