各位前輩,小弟自行學習VBA遇到一些小問題,
想向各位請教一下各位。
本來我是打算寫出只要選取A列就只行計算出E列的答案,
(F列等同A列時,把D列數值加總於E列)
當我點選單格時,E列中可以計算出正確的答案,如下圖。
但當我選取一整列時,E列卻會把數值累計起來,如下圖。
請問我應該在哪裡作出修正?
以下是自己寫下的東西:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim myData As Range, c As Range, cr1 As Range
st1 = Application.Match("code", Columns(1), 0)
ed1 = Application.Match("end", Columns(1), 0)
a1 = Application.Match("code", Rows(st1), 0)
b1 = Application.Match("date", Rows(st1), 0)
c1 = Application.Match("name", Rows(st1), 0)
d1 = Application.Match("qty", Rows(st1), 0)
e1 = Application.Match("total", Rows(st1), 0)
f1 = Application.Match("test", Rows(st1), 0)
Set cr1 = Range(Cells(st1, a1).Offset(1, 0), Cells(ed1, a1))
Set myData = Application.Intersect(Target, cr1)
If myData Is Nothing Then Exit Sub
For Each c In myData
If InStr(1, Cells(c.Row, a1).Value, "end") Then
Range(Cells(c.Row, c1), Cells(c.Row, f1)).ClearContents
ElseIf Cells(c.Row, a1).Value = "" Then
Rows(c.Row).ClearContents
ElseIf Cells(c.Row, a1) > 0 Then
Dim n1 As Integer
n1 = Cells(Rows.Count, a1).End(xlUp).Row
For i1 = st1 + 1 To n1
If Cells(i1, f1) = Cells(c.Row, a1) Then
qty = qty + Cells(i1, d1)
End If
Next
Cells(c.Row, e1) = qty
Else:
Cells(c.Row, e1) = ""
End If
Next
End Sub
問題應該出在下面這個for-loop
For i1 = st1 + 1 To n1
If Cells(i1, f1) = Cells(c.Row, a1) Then
qty = qty + Cells(i1, d1)
End If
Next i1
你要在loop外面先把qty
歸零,否則你的數值會被累加。
qty = 0
For i1 = st1 + 1 To n1
If Cells(i1, f1) = Cells(c.Row, a1) Then
qty = qty + Cells(i1, d1)
End If
Next i1
這種錯誤你可以用逐行執行
與區域變數
視窗去除錯。
當我點選單格時,E列中可以計算出正確的答案
一開始加一列
If Target.Cells.Count > 1 Then Exit Sub