Excel VBA - 从单元格引用中添加或减少单元格中的金额

时间:2014-10-27 04:20:41

标签: excel vba excel-vba

我正在尝试寻找一些VBA代码,只要在发票中发出物品,就可以减少库存数量。例如,如果“键盘”和“鼠标”项目由2和3发出,那么该数字应自动减少在库存“数量”列中的受尊重项目

我已经在搜索解决方案而无法获得解决方案。希望你们能帮助我。

提前谢谢你。

1 个答案:

答案 0 :(得分:0)

如果您可以添加有关值的位置以及发票事件的调用方式的更多信息,则会有所帮助。

您是通过表单运行的吗?还是在工作表上?如果有包含信息的文本框,只需在下面声明输入变量时使用它们。

反正。这很容易被压缩,但我会以更加丰富的方式进行阐述,这样您就可以学习它背后的概念,而不是最简洁的代码。

使用修订后的代码编辑:评论后详细说明。看看PIC

Sub InventoryUpdate()

Dim qtyIn As Integer
Dim qtySold As Integer
Dim sheeteName As String
Dim iRow As Integer
Dim lastStockRow As Integer
Dim lastInvoiceRow As Integer
Dim tProduct As String
Dim sRow As Integer


'Declare the sheetName here once, so you don't have to replace it every time it changes
sheetName = "Sheet1"

'Determine the last rows, unless you know it already, then ignore this.
lastInvoiceRow = Sheets(sheetName).Range("B65536").End(xlUp).Row
lastStockRow = Sheets(sheetName).Range("E65536").End(xlUp).Row

'Loop through the rows of your table. Since you know the range, it's rows 4-10
For iRow = 4 To lastInvoiceRow
    'Set the temp Product name as row, Column B, and the Qty Sold from Column C
    tProduct = Sheets(sheetName).Cells(iRow, 2)
    qtySold = Sheets(sheetName).Cells(iRow, 3)

    For sRow = 4 To lastStockRow
        If Sheets(sheetName).Cells(sRow, 5) = tProduct Then
            qtyIn = Sheets(sheetName).Cells(sRow, 6)
            Sheets(sheetName).Cells(sRow, 6) = qtyIn - qtySold
            Exit For
        End If
    Next sRow

Next iRow

End Sub