I want to write VBA code that will compare two columns from two different sheets.
I have data in Sheet1 column B and in Sheet2 column B.
The formula to compare both columns is in Sheet2: =B2=Sheet1!B2.
Could you please help me to write VBA code for the above formula.
I am not sure how to use the above formula in VBA code.
The basic code to compare is
If Sheet1.Range("B1").Value = Sheet2.Range("B1").Value Then
'Code to execute when criteria is met
Else
'Code to execute when criteria is not met
End If
The else part is optional and can be omitted if you don't need it
If you want to compare the full column there are a few ways to do it.
My favorite is following:
Dim iLastRow As Integer
iLastRow = Sheet1.Cells(Sheet1.Rows.Count, 2).End(xlUp) 'Gets the last row
For i = 1 To iLastRow 'Compares each row and executes the code if
If Sheet1.Range("B" & i).Value = Sheet2.Range("B" & i).Value Then
'Code to execute when criteria is met
Else
'Code to execute when criteria is not met
End If
Next i
If you want to compare the displayed/formatted text of the cell and not the value behind it use .Text instead of .Value (e.g. "10th Sep. 2019" instead of 43718)
Related
I have numerous excel sheets that contain rows that have paired data. Specifically, I need to subtract the first row from the one that follows (e.g., row 2-row 1; row 4-row3; etc.) and place the result into a new row below each pair. My data in each sheet appear as follows:
I am not new to programming languages, but I am new to visual basic.
My current code is:
Sub test() Dim rng As Range
Columns(1).Insert
With Range("b2", Range("b" & Rows.Count).End(xlUp)).Offset(, -1)
.Formula = "=if(mod(row(),2)=1,1,"""")"
.Value = .Value
.SpecialCells(2, 1).EntireRow.Insert
End With
Columns(1).Delete
With Range("a1", Range("a" & Rows.Count) _
.End(xlUp)(2)).Resize(, 3)
.Columns(1).SpecialCells(4).Value = "Difference"
Union(.Columns(2).SpecialCells(4), .Columns(3) _
.SpecialCells(4)).Formula = _
"=r[-1]c-r[-2]c"
End With
End Sub
However, the result is this:
I am mainly interested in calculating the differences between row pairs in the first column shown, but it is clearly not working.
Any help would be greatly appreciated!
Easier to use formulae, rather than VBA.
Go to a second sheet in the file ("Sheet2")
Enter in A1: =Sheet1!A1-Sheet1!A2
On Sheet2, select Rows1 AND 2.
Drag down.
Then depends on what you need to do.
May be Copy | Paste Special | Values to Sheet3, and sort to remove blank rows.
I am just starting out with Excel VBA and to be honest I am not that skilled in using normal Excel either.
I've got one sheet that has unique codes in column C, I also have another sheet that has unique codes in column A (except first rows as they've got column labels).
In case this unique code from sheet 1 is also found in the column in sheet 2, I want column J in the sheet1 to have that code value, otherwise, if it cannot be found, I want it to have #N/A.
Normally in Excel I would do this by selecting J2 and entering following function:
=VLOOKUP(C2,Sheet2!A:A,1,False)
Then I'd just double click the corner of the cell to populate all rows.
How do I do it in VBA? I wrote this code hoping it would do something:
Worksheets("Sheet1").Activate
ActiveSheet.Range("J:J").Value = Application.VLookup(C2,Worksheets("Sheet2").Range("A:A"),1,False)
However, this does not work. I just get #N/A for all cells in the J column. Any suggestions what I can do?
The following code will give you what you want. Note that you would only want to put the formula into rows where values actually exist in column C on sheet1.
Option Explicit
Sub InsertVlookup()
Dim LastRow As Long
LastRow = Sheet1.Cells(Rows.Count, 3).End(xlUp).Row
With Sheet1.Range("J2:J" & LastRow)
.FormulaR1C1 = "=VLOOKUP(RC[-7],Sheet2!C[-9],1,FALSE)"
.Value = .Value
End With
End Sub
I have a file where I need to delete certain columns. I then need to insert a column called 'positive values' and add a formula so that only the positive values from another column are picked up in this new column.
So far I have pieced together the following code to delete the columns I do not need, but I am stuck at how to insert a new column next to an existing column called "net" and then have this column only show the positive values from column net in the relevant cells.
Current code
Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range
Sheets("sheet 1").Select
ColumnsToRemove = Array("acronym", "valueusd", "value gbp")
For Each vItem In ColumnsToRemove
Set A = Rows(8).Find(What:=vItem, LookIn:=xlValues, lookat:=xlPart)
Debug.Print vItem, Not A Is Nothing
If Not A Is Nothing Then A.EntireColumn.Delete
Next
End Sub
Currently I manually insert the new column and enter the formula max(E9,0) so the new column either shows 0 or a value if the value in the other column is greater than 0. Is it possible to automate this part as well.
Thanks in advance.
For Insertion locate the cell and issue:
If Not A Is Nothing Then A.EntireColumn.Insert
To insert a formula, use cell.formula= with the coresponding string value, e.g.
Cells(1, A.column - 1).Formula = "=max(" & cells(9, A.column - 2).Address & ",0)"
Note A as a range of the found value will shift to the right when inserting a column that's why you need - 1 nad - 2 in cell references.
I'm trying to create a macro that will compare the first 4 characters of one column to the first 4 characters of another column in the same row and then mark that row as either Match or No Match.
I did some research and found an Excel formula (=IF(ISNA(MATCH(LEFT(A2,4)&"*",B2:B2,0)),"No Match","Match") which works but I'm not sure how to convert this to VBA. The spreadsheets I'm working with can vary in row length from day to day but they would always have the same number of columns. So I need to be able to: compare column C to column F and write the Match / No Match outcome to column G regardless of the number of rows on the spreadsheet.
Here is an example of the spreadsheet I'm working with that shows the outcome of using the Excel formula.
Any help / suggestions you can provide would be appreciated.
]1
You can use simplified formula and convert it to values if needed (works for active sheet).
Sub CompareLeft()
Dim LRow As Long
LRow = Cells(Rows.Count, "A").End(xlUp).Row
With Range("c2:c" & LRow) '<-- Adjust result column
.FormulaR1C1 = "=IF(LEFT(RC1,4)=LEFT(RC2,4),""Match"",""No Match"")"
.Value = .Value '<-- Optional - convert formula to values
End With
End Sub
I've written a macro in VBA that simply fills in a given cell's value from another cell in that sheet. I do this for lots of cells in the sheet, and I'm doing it like so:
Range("B3").Value = Range("B200")
Range("B4").Value = Range("B201")
'etc.
Now, I am often adding values by inserting new rows, so I might insert a new row
between B200 and B201, which will break the macro because it doesn't autoupdate when
I insert the new row.
How can I code the macro so it autoupdates the cell references when I insert new rows or columns?
My suggestion would be to make sure the ROW you want to retrieve values from has a unique value in it that you can .FIND anytime you want, then grab your values from column B of that found cell's row. So right now you want to get a value in B200 and A200 always has the text in it: "Final Total" and that is unique.
Dim MyRNG As Range
Set MyRNG = Range("A:A").Find("Final Total", LookIn:=xlValues, LookAt:=xlWhole)
Range("B3").Value = Range("B" & MyRNG.Row)
Range("B4").Value = Range("B" & MyRNG.Row + 1)
This is not an answer but an alternative.
Naming your range is the way to go as Shiin suggested but then if you have 500 cells then like I mentioned earlier, naming 500 cells and using them in your code can be very painful. The alternative is to use smart code. Let's take an example
Let's say you have a code like this
Sub Sample()
Range("B3").Value = Range("B200")
Range("B4").Value = Range("B201")
Range("B5").Value = Range("B201")
' And
' So On
' till
Range("B500").Value = Range("B697")
End Sub
The best way to write this code is like this
Sub Sample()
Dim i As Long
For i = 200 To 697
Range("B" & i - 197).Value = Range("B" & i)
Next i
End Sub
and say if you insert a line at say row 300 then simply break the above code in two parts
Sub Sample()
Dim i As Long
For i = 200 To 299
Range("B" & i - 197).Value = Range("B" & i)
Next i
For i = 301 To 698
Range("B" & i - 197).Value = Range("B" & i)
Next i
End Sub
So every time you insert a row, simply break the for loop into an extra part. This looks tedious but is much better than naming 500 cells and using them in your code.
If you are planning to use the macro only once (i.e for 1 time use) then read ahead.
If you are worried that when the user inserts the row then the cells are not updated then you can instead of assigning a value, assign a formula.
For example
Range("B3").Formula = "=B200"
This will put a formula =B200 in cell B3. So next time when you insert a row so that the 200th row moves it's position, you will notice that the formula automatically gets updated in cell B3
HTH
Try giving a name to the range. If you refer to the range by name Excel searches for it and retrieves the rows that defines it. Range names update their definition when new rows are added.
Adding to the above, i think this tutorial illustrates my point:
http://www.homeandlearn.co.uk/excel2007/excel2007s7p6.html this is how to define the name of the range.
This tutorial explains how to use it on macros and vba:
http://excel.tips.net/T003106_Using_Named_Ranges_in_a_Macro.html
I hope this helps :D