以下是一个用于更新库存的按钮的VBA代码示例:
Sub UpdateInventory()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
'设置要更新库存的工作表
Set ws = ThisWorkbook.Worksheets("库存表")
'找到最后一行
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'循环遍历每一行,更新库存
For i = 2 To lastRow
'获取产品名称和新库存数量
Dim productName As String
Dim newQuantity As Integer
productName = ws.Cells(i, 1).Value
newQuantity = ws.Cells(i, 2).Value
'根据产品名称查找库存表中的对应行
Dim inventoryRow As Range
Set inventoryRow = ws.Range("A:A").Find(productName)
'如果找到了对应的行,则更新库存数量
If Not inventoryRow Is Nothing Then
ws.Cells(inventoryRow.Row, 2).Value = newQuantity
Else
'如果找不到对应的行,则在最后一行添加新的库存记录
ws.Cells(lastRow + 1, 1).Value = productName
ws.Cells(lastRow + 1, 2).Value = newQuantity
lastRow = lastRow + 1
End If
Next i
'显示更新成功的消息
MsgBox "库存已更新。"
End Sub
在这个示例代码中,首先设置要更新库存的工作表。然后,通过循环遍历每一行,获取产品名称和新的库存数量。接下来,使用Find
函数在库存表中查找对应的产品名称。如果找到了对应的行,则更新库存数量;如果找不到对应的行,则在最后一行添加新的库存记录。最后,显示更新成功的消息框。
你可以将这段代码复制到Excel的VBA编辑器中,并将其关联到一个按钮的事件处理程序中,以便在点击按钮时执行更新库存的操作。