2017-01-02 127 views
0

當談到VBA時,我非常習慣於初學者,我無法弄清楚如何更新我的宏。VBA宏從一張紙複製數據並粘貼到另一張(在某些條件下)

通常從幾片(所述特定的一個被稱爲SS)並將其粘貼到另一個(MainSheet)它複製數據:

Dim lastrow As Long 

(...)

Lastrowss = Sheets (「SS」).Range(「A1」).End(xlDown).Row 

(。 ..)

For i = 2 To lastrows 

(...)

Sheets("MainSheet").Cells(j, 7).Value = Sheets("SS").Cells(i, 7).Value 'Rec Amount 
Sheets("MainSheet").Cells(j, 9).Value = Sheets("SS").Cells(i, 9).Value * -1 'Paid Amount 

問題在哪裏呢? 該宏僅適用於大約一半的查詢。準確地說:爲銷售購買反映的方式相反。

換句話說 - 宏應該複製第7列和第9列中的數據,並且只有在列D中有「買入」的情況下才將其粘貼到第9列和第7列(不是7和9)。如果有「 「宏應該保持不變。

爲了讓事情看起來更加醜陋:在D列中,您並不總是隻是「賣」或「買」。你也可以看到「賣出來掩蓋」等等,但邏輯仍然是一樣的。

我將不勝感激任何幫助。 謝謝。

+0

我擔心你聲明瞭一個名爲'lastrow'的變量,然後爲一個名爲'Lastrowss'的不同變量賦值,然後爲你的循環使用另一個名爲'lastrows'的變量。請在每個代碼模塊的開頭添加「Option Explicit」。 – YowE3K

+0

這是我的錯字。應該是:對於i = 2對於拉斯特羅斯 – DrBeton

+0

我仍然擔心你聲明一個名爲'lastrow'的變量,然後使用一個名爲'lastrowss'的變量。在每個代碼模塊的開始處添加'Option Explicit',您可以避免這種類型的拼寫錯誤。 – YowE3K

回答

2
If Sheets("SS").Cells(i, 4).Value <> "buy" Then ' <-- add this test 
    Sheets("MainSheet").Cells(j, 7).Value = Sheets("SS").Cells(i, 7).Value 'Rec Amount 
    Sheets("MainSheet").Cells(j, 9).Value = Sheets("SS").Cells(i, 9).Value * -1 'Paid Amount 
Else ' <-- here we inverse the two columns 
    Sheets("MainSheet").Cells(j, 7).Value = Sheets("SS").Cells(i, 9).Value 'Rec Amount 
    Sheets("MainSheet").Cells(j, 9).Value = Sheets("SS").Cells(i, 7).Value * -1 'Paid Amount 

End If 
+0

嗨,謝謝你的幫助。不幸的是它不工作。我得到運行時錯誤'13'類型不匹配 – DrBeton

0

謝謝大家的幫助。 我已經稍微更新了代碼:

If Left(Sheets("SS").Cells(i, 4).Value, 3) <> "Buy" Then 
    Sheets("MainSheet").Cells(j, 7).Value = Sheets("SS").Cells(i, 7).Value 'Rec Amount 
    Sheets("MainSheet").Cells(j, 9).Value = Sheets("SS").Cells(i, 9).Value * -1 'Paid Amount 
Else 
    Sheets("MainSheet").Cells(j, 7).Value = Sheets("SS").Cells(i, 9).Value 'Rec Amount 
    Sheets("MainSheet").Cells(j, 9).Value = Sheets("SS").Cells(i, 7).Value * -1 'Paid Amount 

End If 

似乎現在就工作。

+2

因爲你的答案很大程度上依賴於@ A.S.H的回答,也許接受他的答案對他的努力是公平的。 –

+0

出於好奇,當A.S.H的代碼執行時,爲什麼你的代碼不會給出「類型不匹配」? (所有我能想到的是你的一些「金額」實際上不是金額。) – YowE3K

+0

完成@Scott Holtzman。我對這個論壇的規則不是很熟悉。 – DrBeton

相關問題