Help with VBA: Inserting formula with loop

sam82

New Member
Joined
Jan 24, 2011
Messages
7
Hello,

I import this Excel file that has amounts down one column, and the words buy/sell down two columns over to tell which of those amounts are buy and sell. Unfortunately, buys are not shown as a negative amount (ex: -2,000, or (2,000)). They both show as positive amounts. I'm trying to use VBA to make a formula that will look to see if it's a buy transaction, copy the amount over, and make it negative. I need it to ignore sell transactions as it moves down. Here's what I have:

Sub BuySell()
Range("F2").Select
Buy = 2
Do While ActiveCell.Value <> 0
If ActiveCell.Value = "Buy" Then
ActiveCell.Offset(0, -2).Select
Selection.Copy
ActiveCell.Offset(0, 3).Select 'Range G2
Selection.Paste 'Range G2
ActiveCell.Offset(0, 1).Select 'Range H2
ActiveCell.Formula = "=(G" & Buy & "*-1)"
ActiveCell.Offset(0, -2).Select
Buy = Buy + 1
Else
ActiveCell.Offset(1, 0).Select
Loop
End If

I use to be good in VBA but it's been over two years since I used it last and I can't get this to work!

Thanks,
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
So you have Buy/Sell in column F and you want to copy the value in column D of the same row to column G and put a formula in column H.

Perhaps this?
Code:
Dim LastRow As Long
LastRow = Range("F" & Rows.Count).End(xlUp).Row

Range("G2:G" & LastRow).Formula = "=IF(F2=""BUY"", D2, """")"
Range("H2:H" & LastRow).Formula = "=IF(F2=""BUY"", -D2, """")"
 
Upvote 0

Forum statistics

Threads
1,224,507
Messages
6,179,176
Members
452,893
Latest member
denay

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top