VBA电子表格专栏

Private Sub txtTotal1_Change() Dim Final As Integer If cbOldf_Change() Then olf1 = cbOldf.ActiveCell.Offset(0, 1) Final = oldf_col * quantity ElseIf cbHaribo1_Change() Then haribo1 = cbHaribo1.ActiveCell.Offset(0, 1) + 1 Final = haribo_col * quantity ElseIf cbOldf_Change() = cbHaribo1_Change() Then oldf_1 = cbOldf.ActiveCell.Offset(0, 1) + 1 haribo1 = cbHaribo1.ActiveCell.Offset(0, 1) + 1 Final = oldf_1 + haribo1 * quantity End If If txtQuantity1_Change() Then txtTotal.Value = Final End Sub 

我是新的vba。 我有两个单独的产品工作表(哈里波和旧collections夹)我有combobox从这些工作表中抓取产品和一个文本框input数量。 在产品工作表中,产品名称在A列,价格在B列。我想实现的是能够从combobox中select一个产品名称,在文本框中input一个数量,并获得总价格进行计算,然后显示在“总计”文本框中。

我是新来的,所以请看看我可怕的代码,我给了它一个诚实的5个小时的努力,我现在在我的智慧结束! 我会喜欢一些帮助或请指出正确的方向。

编辑:这是我的工作手册https://www.dropbox.com/s/49iym4exbcgmhcq/Main%20Page.xlsm我正在做这个大学,你可能会猜测通过它

尝试使用此代码来设置总数:

 Private Sub SetTotal() Dim dblTotal As Double Dim dblQuantity As Double If IsNumeric(Me.txtQuantity1) Then dblQuantity = CDbl(Me.txtQuantity1) End If If cbHaribo1.Value <> "" Then dblTotal = dblQuantity * GetPrice(Sheets("HARIBO").Range("A:B"), cbHaribo1.Value) End If If Me.cbOldf.Value <> "" Then dblTotal = dblTotal + dblQuantity * GetPrice(Sheets("OLDFAVORITES").Range("A:B"), cbOldf.Value) End If Me.txtTotal1 = Format(dblTotal, "0.00") End Sub Private Function GetPrice(rng As Range, strProduct As String) As Double On Error GoTo ErrorHandler GetPrice = WorksheetFunction.VLookup(strProduct, rng, 2, False) Exit Function ErrorHandler: GetPrice = 0 End Function 

要触发这个代码,你需要插入这些事件:

 Private Sub cbHaribo1_Change() SetTotal End Sub Private Sub cbOldf_Change() SetTotal End Sub Private Sub txtQuantity1_Change() SetTotal End Sub 

请注意,表单有点模棱两可 – 目前代码适用于Haribo和旧collections夹。 更好的是你prodive第二个数量字段 – 或插入一个选项框灰色哈博波或旧collections夹…