多个项目的小计计算 - Visual Basic

Posted

技术标签:

【中文标题】多个项目的小计计算 - Visual Basic【英文标题】:Subtotal Calculation for Numerous Items - Visual Basic 【发布时间】:2015-03-22 20:14:56 【问题描述】:
Public Class Form1
'Modular Variable Declaration Section
Dim mintOrdersPlacedToday As Integer
Dim msngTotalOfOrdersToday As Single
Dim msngShippingCost As Single = -1
Const csngSalesTaxRate As Single = 0.0625
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    'Local Variable Declaration Section
    Dim sngShirtPrice As Single = 10
    Dim sngPremiumShirtPrice As Single = 20
    Dim sngHatsPrice As Single = 15
    Dim sngStickersPrice As Single = 5
    Dim sngSubTotal As Single
    Dim sngSalesTax As Single
    Dim sngOrderTotal As Single
    Dim intQuantity As Integer
    'Data Input Section
    If msngShippingCost = -1 Then
        MessageBox.Show("Please choose a shipping method", "Error", MessageBoxButtons.OK)    'Displays an error messsage when no shipping method is chosen
        Exit Sub 'Terminates the click event to allow shipping method to be chosen first
    End If

    Try     'Checks to see if the price is a valid number.
        'If it is, then it is assigned to the quantity variable, if not, error message and the event is halted.
        intQuantity = txtShirts.Text
    Catch ex As Exception
        MessageBox.Show("Please enter a valid number of Shirts.", "Error", MessageBoxButtons.OK)    'Displays an error messsage when there is an invalid number
        txtShirts.Text = ""  'Clears the text box
        txtShirts.Focus()    'Puts the cursor in the price textbox
        Exit Sub    'Terminates the click event to allow valid input.
    End Try

    Try

    Catch ex As Exception

    End Try


    'Calculation Section
    sngSubTotal = intQuantity * sngShirtPrice  'Calculates the subtotal
    sngSalesTax = sngSubTotal * csngSalesTaxRate    'Calculates Sales Tax based on the sales tax rate constant
    sngOrderTotal = sngSubTotal + sngSalesTax + msngShippingCost 'Calculates total for the sale
    mintOrdersPlacedToday = mintOrdersPlacedToday + 1   'Calculates the number of orders placed today, adds one to the previous number
    msngTotalOfOrdersToday = msngTotalOfOrdersToday + sngOrderTotal 'Calculates the Total of all the orders placed today



    'Output section
    lblShowSubTotal.Text = FormatCurrency(sngSubTotal)  'Displays the Subtotal
    lblShowSalesTax.Text = FormatCurrency(sngSalesTax)  'Displays the Sales Tax
    lblShowOrderTotal.Text = FormatCurrency(sngOrderTotal)  'Displays the Order Total
    lblShowOrdersPlacedToday.Text = mintOrdersPlacedToday   'Displays the Orders placed today
    lblShowTotalOfOrders.Text = FormatCurrency(msngTotalOfOrdersToday)  'Displays the Total of the Orders placed today
    lblShowShippingCost.Text = FormatCurrency(msngShippingCost)  'Displays the total of the shipping cost
End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Dim result = MessageBox.Show(" Are you sure you want to exit?", "Are you sure?", MessageBoxButtons.YesNo) 'Shows a messagebox for the user asking if they want to exit the program and gives them options.
    If result = DialogResult.Yes Then   'States that if the user clicks Yes, the program will close
        Me.Close() 'Exits the program
    End If
End Sub

Private Sub btnClearCurentSale_Click(sender As Object, e As EventArgs) Handles btnClearCurentSale.Click
    'Clears the information from current sale and resets the form for the next sale
    radPickup.Checked = True 'Checks the Pickup radio button
    radPickup.Checked = False 'Unchecks the Pickup radio button
    btnCalculate.Enabled = True 'Enables the Calculate button
    msngShippingCost = -1   'Sets Shipping Cost to -1
    lblShowShippingCost.Text = "" 'Clears the Shipping Cost label
    lblShowOrderTotal.Text = "" 'Clears the Order Total label
    lblShowSalesTax.Text = "" 'Clears the Sales Tax label
    lblShowSubTotal.Text = "" 'Clears the Sub Total label
    txtShirts.Text = "" 'Clears the Shirts text box
    txtShirts.Focus()   'Puts the cursor in the Shirts text box
End Sub

Private Sub radPickup_CheckedChanged(sender As Object, e As EventArgs) Handles radPickup.CheckedChanged
    msngShippingCost = 0    'Sets shipping cost as $0
    lblShowShippingCost.Text = "Free"   'Sets Shipping Cost label to show $0
    lblShowOrderTotal.Text = "" 'Clears the Order Total label
End Sub

Private Sub radGround_CheckedChanged(sender As Object, e As EventArgs) Handles radGround.CheckedChanged
    msngShippingCost = 6.75 'Sets shipping cost as $6.75
    lblShowShippingCost.Text = FormatCurrency(6.75, 2)  'Sets Shipping Cost label to show $6.75
    lblShowOrderTotal.Text = "" 'Clears the Order Total label
End Sub

Private Sub radTwoDay_CheckedChanged(sender As Object, e As EventArgs) Handles radTwoDay.CheckedChanged
    msngShippingCost = 12   'Sets shipping cost as $12
    lblShowShippingCost.Text = FormatCurrency(12, 2)    'Sets Shipping Cost label to show $12
    lblShowOrderTotal.Text = "" 'Clears the Order Total label
End Sub

Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
    'Clears the information for everything on the form
    txtShirts.Text = "" 'Clears the Shirts text box
    txtShirts.Focus()   'Puts the cursor in the Shirts text box
    lblShowSubTotal.Text = "" 'Clears the Sub Total label
    lblShowSalesTax.Text = "" 'Clears the Sales Tax label
    lblShowShippingCost.Text = "" 'Clears the Shipping Cost label
    lblShowOrderTotal.Text = "" 'CLears the Order Total label
    lblShowOrdersPlacedToday.Text = "" 'Clears the Orders Placed Today label
    lblShowTotalOfOrders.Text = "" 'Clears the Total of Orders Today label
    mintOrdersPlacedToday = 0   'Resets the counter
    msngTotalOfOrdersToday = 0  'Resets the accumulator
End Sub
End Class

我的问题是:我会怎么做才能让用户在众多项目文本框中输入数量时进行计算?我卡住了,请帮忙。

左边有一个标签,右边有一个文本框。标签上写着“衬衫(10.00 美元)”,文本框是他们输入要购买的衬衫数量的地方。其他 3 个标签旁边的其他 3 个文本框也是如此,它们输入他们要购买的商品的数量。然后他们在选择运输后点击计算,它给他们一个小计和所有其余的。除了获得小计所需的费用外,不要担心运输或其他任何事情。我需要这样做,以便用户可以在一个、两个、三个或所有文本框中输入一个数量,然后点击计算以获得适当的小计。对不起,如果我第一次没有正确解释。这就是我所需要的,一种让计算正常工作的方法。请帮忙! :c

【问题讨论】:

【参考方案1】:

这是一个简单的订购系统,它极大地简化了计算,因为您只需在订单中添加/删除产品。

示例:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim beers = new ProductOrder(New BeerProduct, 20)
        Dim tacos = new ProductOrder(New TacosProduct, 100)
        Dim order As New Order
        order.Products.Add(beers)
        order.Products.Add(tacos)

        Dim totalForBeers = beers.Total
        Dim totalForTacos = tacos.Total
        Dim grandTotal = order.GrandTotal
    End Sub
End Class

支持所有这些的类:

有价格的产品:

Public MustInherit Class Product
    MustOverride ReadOnly Property Price() As Decimal
End Class

部分产品:

Public Class BeerProduct
    Inherits  Product

    Public Overrides ReadOnly Property Price() As Decimal
        Get
            Return 10.0D
        End Get
    End Property
End Class

Public Class TacosProduct
    Inherits  Product

    Public Overrides ReadOnly Property Price() As Decimal
        Get
            Return 5.0D
        End Get
    End Property
End Class

订单相关类型:

Public Class ProductOrder
    Property Product() As Product
    Property Quantity() As Integer

    ReadOnly Property Total As Decimal
        Get
            Return Product.Price*Quantity
        End Get
    End Property


    Public Sub New(ByVal product As Product, ByVal quantity As Integer)
        Me.Product = product
        Me.Quantity = quantity
    End Sub
End Class

Public Class Order
    Private ReadOnly _products As List(Of ProductOrder)

    Public Sub New()
        _products = New List(Of ProductOrder)()
    End Sub

    ReadOnly Property Products() As List(Of ProductOrder)
        Get
            return _products
        End Get
    End Property

    ReadOnly Property GrandTotal() As Decimal
        Get
            Return Products.Sum(Function (x) x.Total)
        End Get
    End Property
End Class

待办事项

以友好的方式呈现,例如使用DataGrid 允许用户使用ComboBox 或其他方式添加Product 等等...

请注意,我没有讨论这些方面,因为您没有告诉您使用的是什么框架(WPF 或 Forms)。

祝你好运!

【讨论】:

你把我弄丢了。我正在使用表格。我将在一秒钟内发布整个代码。回来查看对帖子的编辑。【参考方案2】:

针对完整编辑的问题的编辑答案:

我已删除并添加了一些内容。 别忘了加上运费。 不要只是复制粘贴这个。研究它,看看它是如何工作的,然后调整你的代码。

但不至于过于复杂,最简单的方法是将每个产品分别求和,然后合并。

看看这是不是你要找的。 *笔记。毕竟,最好只在文本框中指定“0”而不是使用 Catch ex。

 Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    'Local Variable Declaration Section
    Dim sngShirtPrice As Single = 10
    Dim sngPremiumShirtPrice As Single = 20
    Dim sngHatsPrice As Single = 15
    Dim sngStickersPrice As Single = 5
    Dim sngSalesTax As Single

    Dim sngOrderTotal As Single


    Dim StickersQuantity As Integer
    Dim sngStickersTotal As Single

    Dim ShirtsQuantity As Integer
    Dim sngShirtsTotal As Single

    Dim HatsQuantity As Integer
    Dim sngHatsTotal As Single


    If txtShirts.Text = Nothing Then

        txtShirts.Text = "0"

    End If

    If txtHats.Text = Nothing Then

        txtHats.Text = "0"

    End If

    If txtStickers.Text = Nothing Then

        txtStickers.Text = "0"

    End If

    ShirtsQuantity = txtShirts.Text
    HatsQuantity = txtHats.Text
    StickersQuantity = txtStickers.Text


    'Calculation Section
    sngShirtsTotal = ShirtsQuantity * sngShirtPrice
    sngHatsTotal = HatsQuantity * sngHatsPrice
    sngStickersTotal = StickersQuantity * sngStickersPrice

    Dim TTotal As Single

    TTotal = sngShirtsTotal + sngHatsTotal + sngStickersTotal


    sngSalesTax = TTotal * csngSalesTaxRate    'Calculates Sales Tax based on the sales tax rate constant


    sngOrderTotal = TTotal + sngSalesTax + msngShippingCost 'Calculates total for the sale
    mintOrdersPlacedToday = mintOrdersPlacedToday + 1   'Calculates the number of orders placed today, adds one to the previous number
    msngTotalOfOrdersToday = msngTotalOfOrdersToday + sngOrderTotal 'Calculates the Total of all the orders placed today



    'Output section
    lblShowSubTotal.Text = FormatCurrency(TTotal)  'Displays the Subtotal
    lblShowSalesTax.Text = FormatCurrency(sngSalesTax)  'Displays the Sales Tax
    lblShowOrderTotal.Text = FormatCurrency(sngOrderTotal)  'Displays the Order Total
    lblShowOrdersPlacedToday.Text = mintOrdersPlacedToday   'Displays the Orders placed today
    lblShowTotalOfOrders.Text = FormatCurrency(msngTotalOfOrdersToday)  'Displays the Total of the Orders placed today
    lblShowShippingCost.Text = FormatCurrency(msngShippingCost)  'Displays the total of the shipping cost
End Sub

你的代码有点乱...我只对按钮点击事件进行了更改。

【讨论】:

您不应该使用 Try-Catch 进行计算。验证输入是一种更简洁的解决方案。 塔夫斯,非常感谢您的帮助。我实际上有一个尝试,我没有输入我的所有代码,只是我遇到问题的部分,它让小计可以正确计算许多项目。并且让用户能够一次输入多个项目的数量。有没有机会我可以让你使用 Skype 或其他方式与我聊天?只是文字聊天。直到我彻底解决这个问题?我将不胜感激。 另外,我忘了在顶部也定义了dim intQuantity as Integer 我已经更新了我的回复。我也认为简单地将“0”分配给文本框而不是捕捉 ex 更好。

以上是关于多个项目的小计计算 - Visual Basic的主要内容,如果未能解决你的问题,请参考以下文章

触发计算小计

在具有多个因子(字符)变量的数据框中聚合(小计)

rails方法来计算小计和总计

项目的权限设计的小计

VBA添加具有可变范围的小计

BBS小计