I have a sheet which has columns (eg:- A to Z) with decimal values.
Column A could have 10 rows and Column B could have 100 rows.
The user wants an option of subtracting any 2 columns.
So, it means that the user will require a form which will have something like
Choose 1st column : say A
Choose 2nd column : say F
And then press button 'Substract'
It will give result in a column 'AA' as ColumnF- ColumnA for all the values in these columns, if data exists in either of the two.
Can someone please give me the VBA code to achieve this?Thanks
In atach is code: instead column A input 1, instead column B input 2, etc.
Last edited by pera68; 06-28-2011 at 01:05 PM.
Sub calculate() Dim column1, column2, mesage1, mesage2 Dim i As Long mesage1 = "Please input 1st column:" column1 = InputBox(mesage1) column1 = Val(column1) mesage2 = "Please input 2nd column:" column2 = InputBox(mesage2) column2 = Val(column2) For i = 2 To 200 If Worksheets(1).Cells(i, column1).Value = "" And Worksheets(1).Cells(i, column2).Value = "" Then Exit Sub Worksheets(1).Cells(i, 27).Value = Worksheets(1).Cells(i, column2).Value - Worksheets(1).Cells(i, column1).Value Next i Range("A1").Select End Sub
I add one row in code (after Dim i As Long):
Sub calculate() Dim column1, column2, mesage1, mesage2 Dim i As Long Worksheets(1).Columns(27).ClearContents mesage1 = "Please input 1st column:" column1 = InputBox(mesage1) column1 = Val(column1) mesage2 = "Please input 2nd column:" column2 = InputBox(mesage2) column2 = Val(column2) For i = 2 To 200 If Worksheets(1).Cells(i, column1).Value = "" And Worksheets(1).Cells(i, column2).Value = "" Then Exit Sub Worksheets(1).Cells(i, 27).Value = Worksheets(1).Cells(i, column2).Value - Worksheets(1).Cells(i, column1).Value Next i Range("A1").Select End Sub
Many Thanks pera68. Why doesn't column AA show negative values? Plz help!
If value in column2 is less than value in column1 then results is negative number.
If you wish you change operator And into Or in line "If Worksheets(1).Cells(i,column1),value.... and results in column AA is blank.
TYVM for your patience.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks