2017-04-05 68 views
-1

enter image description here沒有得到任何編譯錯誤,但是,沒有得到任何輸出以及

Option Explicit 

Sub dowhileloop() 

Dim x As Long 
Dim sumX As Long 
Dim ws As Worksheet 
Dim n As Integer 

Set ws = ThisWorkbook.Worksheets("test data") 

For x = 2 To ws.Cells(ws.Rows.Count, "B").End(xlUp).Row 
sumX = ws.Cells(x, 5).Value2 
n = 1 

If ws.Cells(x, 2) = ws.Cells(x + n, 2) And ws.Cells(x, 4) = ws.Cells(x + n, 
4) Then 
    sumX = sumX + ws.Cells(x + n, 5).Value 
    ws.Cells(x + n, 6) = sumX 
Else 
    n = n + 1 

End If 
Next x 

End Sub 

我使用的邏輯是不正確的得到我想要的輸出。這是我第一次寫VBA。

請對此建議。

+0

我看不到您將任何值重新放在工作表上。某處你需要像'ws.Cells(x + n,5)= sumX'這樣的東西。 –

+0

非常感謝回覆。它的工作,我得到的輸出,但它只是乘以2,mayb我用的邏輯是行不通的。 你可以看到我附加的圖像問題,它顯示了我想要的輸出 非常感謝 –

+0

瞭解你的圖像有點難 - 在同一張紙上是輸入/輸出嗎?它是否顯示列A:E,列C大多是黑色的? –

回答

0

我可以看到的第一個問題是您不會將值重新放在工作表上,正如我的第一條評論中所述。
也許你後,你End If需要的東西,如:
ws.Cells(x,2) = sumX

在循環的邏輯也是不正確的。據我可以看到這是它在做什麼:

迴路1
x = 2
sumX = 78(細胞(2,5)=範圍E2)
n = 0

使用這些值的IF條件聲明:

If cell B2 = cell B2 AND cell D2 = cell D2 then <this is always true> 
    sumX = 78 + 78 
else 
    n = 1 
end if 

由於條件爲真,那麼n沒有increa sed,因此循環2說明:

sumX = 64 
    If cell B3 = cell B3 and cell D3 = cell D3 then <again true> 
     sumX = 64 + 64 
    else 
     n = n +1 
    end if 

也許在循環之前使用n=1

相關問題