基于gpf_npno对Sheet171的Qty列进行SUMIF求和技术咨询
按gpf_npno字段对Qty列实现SUMIF求和的VBA方案
需求与现有代码
工作表名称为171,需按gpf_npno字段对Qty列进行SUMIF求和。目前已完成用户窗体布局,仅编写了搜索按钮的基础VBA代码,尚未实现求和功能,现有代码如下:
Private Sub CommandButton1_Click() Dim searchValue As String Dim foundCell As Range ' Get the search query from the textbox searchValue = TextBox1.Value ' Assuming your data is in Sheet1, Column A Set foundCell = Sheets("171").Columns("A:A").Find(What:=searchValue, LookIn:=xlValues, LookAt:=xlWhole) If Not foundCell Is Nothing Then ' Value found, display the address of the cell 'MsgBox "Found at " '& foundCell.Address Else ' Value not found MsgBox "tang ina mooo. I type mo nang maaayos!" End If End Sub
求和功能实现方案
直接在现有代码基础上扩展逻辑即可,步骤如下:
确认列对应关系
先确定gpf_npno和Qty分别所在的列(示例中假设gpf_npno在A列,Qty在B列,你可根据实际数据调整)。修改后的完整代码
加入WorksheetFunction.SumIf实现求和,同时补充空值检查、错误处理:
Private Sub CommandButton1_Click() Dim searchValue As String Dim sumResult As Double Dim gpfColumn As Range Dim qtyColumn As Range ' 获取文本框中的搜索值 searchValue = TextBox1.Value ' 定义gpf_npno列和Qty列(根据实际数据调整列号) Set gpfColumn = Sheets("171").Columns("A:A") Set qtyColumn = Sheets("171").Columns("B:B") ' 检查搜索值是否为空 If searchValue = "" Then MsgBox "请输入要查询的gpf_npno值!" Exit Sub End If ' 计算对应Qty的总和,处理无匹配时的错误 On Error Resume Next sumResult = WorksheetFunction.SumIf(gpfColumn, searchValue, qtyColumn) On Error GoTo 0 ' 输出结果 If WorksheetFunction.CountIf(gpfColumn, searchValue) > 0 Then MsgBox "gpf_npno为" & searchValue & "的Qty总和为:" & sumResult Else MsgBox "tang ina mooo. I type mo nang maaayos!" End If End Sub
- 代码关键说明
- 列号调整:如果
gpf_npno在C列、Qty在E列,直接把Columns("A:A")改成Columns("C:C"),Columns("B:B")改成Columns("E:E")即可。 - 错误处理:
On Error Resume Next避免无匹配值时SumIf函数返回错误。 - 结果判断:用
CountIf确认是否存在匹配值,避免总和为0时误判为无数据。
- 列号调整:如果
内容的提问来源于stack exchange,提问作者LEO PEJE
相关产品推荐
相关产品推荐

