iT邦幫忙

0

Excel vba (Worksheet_SelectionChange + 條件變數加總問題)

各位前輩,小弟自行學習VBA遇到一些小問題,
想向各位請教一下各位。

本來我是打算寫出只要選取A列就只行計算出E列的答案,
(F列等同A列時,把D列數值加總於E列)

當我點選單格時,E列中可以計算出正確的答案,如下圖。
https://ithelp.ithome.com.tw/upload/images/20180712/20110619CzqG5PHvaN.jpg

但當我選取一整列時,E列卻會把數值累計起來,如下圖。
https://ithelp.ithome.com.tw/upload/images/20180712/20110619mPxhFOmE0L.jpg

請問我應該在哪裡作出修正?

以下是自己寫下的東西:

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
可不可以把程式碼包起來(用CTRL+ALT+C),比較好閱讀。
Else:
為何Else後方要接冒號?
arhoi iT邦新手 5 級 ‧ 2018-07-13 10:08:56 檢舉
不需要的嗎?我家中的參考書中也有這樣的一個冒號。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
paicheng0111
iT邦大師 5 級 ‧ 2018-07-13 10:20:28
最佳解答

問題應該出在下面這個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

這種錯誤你可以用逐行執行區域變數視窗去除錯。

arhoi iT邦新手 5 級 ‧ 2018-07-13 10:26:56 檢舉

感謝。
因為剛開始自己學,對VBA的寫作方法還不很了解,
至今都只是看書和在網上找自己想書的東西再加在一加的感覺。((汗))

這種錯誤你可以用逐行執行與區域變數視窗去除錯。

是按F8來查看的那個嗎?

在VBE中打開區域變數視窗(按 ALT + V 然後按 ALT + S),然後逐行執行(按 F8),檢查變數的值是否符合你的預期。

arhoi iT邦新手 5 級 ‧ 2018-07-13 11:17:31 檢舉

明白,感謝指導。

1
海綿寶寶
iT邦大神 1 級 ‧ 2018-07-13 09:49:41

當我點選單格時,E列中可以計算出正確的答案

一開始加一列

If Target.Cells.Count > 1 Then Exit Sub
arhoi iT邦新手 5 級 ‧ 2018-07-13 10:07:55 檢舉

感謝解答。

可能是我的發問方法不太好,
使用你提供的方法的話,的確可以限制了累積計算的問題,
但同時也限制了一次只能選取一格來運算。

我在嘗試找尋一次選取多格,但也能計算出正確答案的方法,
即像上方圖二時選取整個A列,但答案會計算出圖一中E列的結果。

問題解決就好

arhoi iT邦新手 5 級 ‧ 2018-07-13 10:30:11 檢舉

謝謝啊

我要發表回答

立即登入回答