一维数组自动舍入取值

时间:2018-06-22 13:39:09

标签: vba excel-vba excel

当我做一个求和或有代码循环并将值自动添加到数组中时,数组会从电子表格中提取信息并进行乘法运算,得出一个带有2个小数点的数字。有任何想法吗? Screenshot of values being taken from spreadsheet

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)

1 个答案:

答案 0 :(得分:0)

多亏了Scott Craner,

Dim TotalWeight as Double是正确的答案。