copy lane from different sheet if the same value - vba

I have 5 columns in sheet1, and the same in sheet 2.The name of the product is in A. But sometimes the caracteristics of the products (in B,C,D,E) can change in sheet 2. I want that it actualize the caracteristics in Sheet1.
I tried a Vlookup, but it works only zith one Cell
Sub test()
With Sheets("Feuil1")
.Range("B1").Value = WorksheetFunction.VLookup(.Range("A1").Value, Sheets("Feuil2").Range("A1:B100"), 2, False)
End With
End Sub
Moreover, I cant copy all the line because the colomn F should not changeā€¦ And products in sheet1 in column A are not tidy and get some duplicates...

You need a loop for this to update each row and you need to update each column as well.
I recommend to use WorksheetFunction.Match instead so you only need to match once per row to get the row number and then you can copy the desired values of that row.
Option Explicit
Public Sub UpdateData()
Dim WsDest As Worksheet 'destination workbook to write in
Set WsDest = ThisWorkbook.Worksheets("Feuil1")
Dim WsSrc As Worksheet 'source workbook to match with
Set WsSrc = ThisWorkbook.Worksheets("Feuil2")
Dim LastRow As Long 'last used row in workbook
LastRow = WsDest.Cells(WsDest.Rows.Count, "A").End(xlUp).Row
Dim iRow As Long, MatchedRow As Long
For iRow = 1 To LastRow 'loop through all rows from row 1 to last used row and update each row
MatchedRow = 0 'initialize
On Error Resume Next 'if no match found then ignore error
MatchedRow = WorksheetFunction.Match(WsDest.Cells(iRow, "A"), WsSrc.Columns("A"), 0) 'get the row number of the match
On Error GoTo 0 'reactivate error reporting
'if it didn't match then MatchedRow is still 0
If MatchedRow > 0 Then 'if a match was found then copy values
WsDest.Cells(iRow, "B").Value = WsSrc.Cells(MatchedRow, "B").Value
WsDest.Cells(iRow, "C").Value = WsSrc.Cells(MatchedRow, "C").Value
WsDest.Cells(iRow, "D").Value = WsSrc.Cells(MatchedRow, "D").Value
WsDest.Cells(iRow, "E").Value = WsSrc.Cells(MatchedRow, "E").Value
Else
'didn't find a match
'you can remove the Else part if you want to do nothing here
End If
Next iRow
End Sub
If the columns you want to copy are continous like B, C, D, E you can do it in one copy action which is faster than 4 copy actions (1 for each column):
WsDest.Range("B" & iRow & ":E" & iRow).Value = WsSrc.Range("B" & MatchedRow & ":E" & MatchedRow).Value

Related

Looping and finding similar number in VBA

I am very new to VBA. Just started reading it up 2 days ago. I am wondering how could I write a VB codes assigned to a button to read through the whole column and search for similar numbers.
After that identifying similar numbers, it would need to move on to another column to check if the character in the column are same too.
If both of the logic = true . How can i change the cell of the value of another column?
Sample data
For the current example. The code should know that the first column had matching numbers. After that it will check for the name which is "a" in the example. After that it will automatically change the point to 1 and 0. If there are 3 same ones it will be 1,0,0 for the point
You may try recording whatever you want to do with record macros first, then filter out the codes that are not necessary. If you do not know how to record it using macros, click on the link below. You can learn from the recorded macros and slowly improvise your codes in the future from the experience you may gain.
Here's [a link] (http://www.dummies.com/software/microsoft-office/excel/how-to-record-a-macro-in-excel-2016/)
As per image attached in image I am assuming numbers are in Column A, column to check characters is Column J and result needs to be displayed in Column O then try following code.
Sub Demo()
Dim dict1 As Object
Dim ws As Worksheet
Dim cel As Range, fCell As Range
Dim lastRow As Long, temp As Long
Dim c1
Set dict1 = CreateObject("Scripting.Dictionary")
Set ws = ThisWorkbook.Sheets("Sheet2") 'change Sheet2 to your data sheet
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row with data in Column A
c1 = .Range("A2:A" & lastRow)
For i = UBound(c1, 1) To 1 Step -1 'enter unique values with corresponding values in dict1
dict1(c1(i, 1)) = .Range("J" & i + 1) '+1 for Row 2
Next i
Set fCell = .Range("A2")
For Each cel In .Range("A2:A" & lastRow) 'loop through each cell in Column A
temp = WorksheetFunction.CountIf(.Range(fCell, cel.Address), cel) 'get count
If temp > 1 Then
If cel.Offset(0, 9) = dict1(cel.Value) Then
cel.Offset(0, 14).Value = 0
Else
cel.Offset(0, 14).Value = 1
End If
Else
cel.Offset(0, 14).Value = 1
End If
Next cel
End With
End Sub
EDIT
Sub Demo()
Dim ws As Worksheet
Dim lastRow As Long
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Sheets("Sheet2") 'change Sheet3 to your data range
With ws
lastRow = .Cells(.Rows.count, "A").End(xlUp).Row 'last row with data in Column A
.Range("O2").Formula = "=IF(MOD(SUMPRODUCT(($A$2:$A2=A2)*($J$2:$J2=J2)),3)=1,1,0)" 'enter formula in Cell O2
.Range("O2").AutoFill Destination:=.Range("O2:O" & lastRow) 'drag formula down
.Range("O2:O" & lastRow).Value = .Range("O2:O" & lastRow).Value 'keep only values
End With
Application.ScreenUpdating = True
End Sub

How to find a certain string and then take that string and search it in other cell in vba?

How can I find a particular String and then copy that string, search for it in a different cell then if I find the correct string on the other cell, go to the corresponding cell and copy and paste it into another cell? I keep on getting an error while I am using Instr then another Instr. Any suggestion please anyone. If you see the attached then basically what i am trying to do is First find H which is in michale, then copy michale and search for it in A column, once i find it in A column i go to corresponding column and copy Pick-me* paste it any where in sheet.
Sub ex_find()
Dim ws As Worksheet, m As String, lastrow As Long
Set ws = ActiveWorkbook.Worksheets("Sheet3")
lastrow = ws.UsedRange.Rows.Count + 1
For i = 2 To lastrow
m = ws.Cells(i, 5)
If InStr(ws.Cells(i, 5), "h") > 0 Then
InStr(ws.Cells(i, 1), "m") = 0
End If
Next
End Sub
Your question confuses me a little. I think you want to search for an "h" in values of column "F" and when found search column "A" for the value of found cell in column "F". Then you want to do something with a "corresponding cell"
Sub ex_find()
Dim ws As Worksheet, m As String, lastrow As Long, myArray() As Variant
Set ws = ActiveWorkbook.Worksheets("Sheet3")
lastrow = ws.UsedRange.Rows.Count + 1
For i = 1 To lastrow
If InStr(1, ws.Range("F" & i).Value, "h") <> 0 Then
With ws.Range("a1:a" & lastrow)
Set c = .Find(ws.Range("F" & i).Value, LookIn:=xlValues)
If Not c Is Nothing Then
'firstAddress = c.Address
'Do
'This is where you put your code to change "corresponding cell"
'Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
End If
Next i
End Sub

Copy and Pasting Data based on Cell Input

I am attempting to copy and paste Rows from an original sheet (Ticket Sales) to a new Sheet (Rachel) based on the value in a specific Column for each Row (Column U). I want all the sales from Rachel to be copied over to another sheet, pretty much. No change in the formatting for the second sheet. This is what I have so far:
Sub CopyRachelDataPaste()
Dim i, LastRow
'Get Last Row
LasRow = Sheets("Ticket Sales").Range("A" & Rows.Count).End(xlUp).Row
'Clear Contents
Sheets("Rachel").Range("A2:AB3000").ClearContents
For i = 2 To LastRow
If Sheets("Ticket Sales").Cells(i, "U").Value = "Rachel" Then
Sheets("Ticket Sales").Cells(i, "U").EntireRow.Copy Destination:=Sheets("Rachel").Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next i
End Sub
you must properly reference worksheet in all range definitions
like follows:
Option Explicit
Sub CopyRachelDataPaste()
Dim i As Long, lastRow As Long
Worksheets("Rachel").Range("A2:AB3000").ClearContents 'Clear Contents
With Worksheets("Ticket Sales") '<--| reference ticket worksheet
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row '<--| get referenced worksheet column "A" last non empty row
For i = 2 To lastRow
If .Cells(i, "U").Value = "Rachel" Then .Cells(i, "U").EntireRow.Copy Destination:=Worksheets("Rachel").Range("A" & Worksheets("Rachel").Rows.Count).End(xlUp).Offset(1)
Next i
End With
End Sub

Conditional formatting cells between sheets and outputing to a seperate cell

Sub MatchLiquor()
Dim lastRowOne As Long
Dim lastRowTwo As Long
Dim sheetNameOne As String
Dim sheetNameTwo As String
sheetNameOne = "Recipies" 'Recipies Sheet
sheetNameTwo = "Liquor Breakdowns" 'Liquor Breakdowns
lastRowOne = Sheets(sheetNameOne).Range("B" & Rows.Count).End(xlUp).Row
lastRowTwo = Sheets(sheetNameTwo).Range("A" & Rows.Count).End(xlUp).Row
For lRow = 2 To lastRowOne 'Loop through all rows
For lRowTwo = 2 To lastRowTwo 'Loop through all rows
If Sheets(sheetNameOne).Cells(lRow, "B") = Sheets(sheetNameTwo).Cells(lRowTwo, "A") Then
Sheets(sheetNameOne).Cells(lRow, "C") * Sheets(sheetNameOne).Cells(lRowTwo, "E") Then
End If
Next lRowTwo
Next lRow
End Sub
In sudo, what I'm attempting to accomplish is such:
Search through all rows of sheetA for "name" and compare to sheetB "name"
Upon being found, multiply different value in sheetA with different value in sheetB; output values into different cell in sheetA (example E).
I haven't yet figured out how to output, or even if this will work.
Ideas?
There was some confusion as to which worksheets were used where and no target for the product on a match was provided but this should clear up your loops.
Sub MatchLiquor()
Dim lastRowOne As Long, lastRowTwo As Long, prodct As Double
Dim sheetNameOne As String, sheetNameTwo As String
sheetNameOne = "Recipies" 'Recipies Sheet
sheetNameTwo = "Liquor Breakdowns" 'Liquor Breakdowns
With Sheets(sheetNameOne)
lastRowOne = .Range("B" & Rows.Count).End(xlUp).Row
lastRowTwo = Sheets(sheetNameTwo).Range("A" & Rows.Count).End(xlUp).Row
For lRow = 2 To lastRowOne 'Loop through all rows on Recipies Sheet
For lRowTwo = 2 To lastRowTwo 'Loop through all rows on Liquor Breakdowns
If .Cells(lRow, "B") = Sheets(sheetNameTwo).Cells(lRowTwo, "A") Then
prodct = .Cells(lRow, "C").Value * Sheets(sheetNameTwo).Cells(lRowTwo, "E").Value
'do something with prodct
.cells(lRow, "E") = prodct
Exit For 'found match and computed product; no need to continue this lRowTwo
End If
Next lRowTwo
Next lRow
End With
End Sub
If a match was found and a product calculated (and put somewhere) there is no need to continue running through the internal nested loop with lRowTwo. Just Exit For which will take you back to the outside loop and the next lRow.
Using Sheets(sheetNameOne) in a With ... End With statement cuts down the parent worksheet references by half.

Copy/Paste multiple rows in VBA

I am attempting to do a simple copy row, paste row within a workbook. I've searched threads and tried changing my code multiple times to no avail.
The one that comes closest to working is this but it only copies a single instance of matching criteria.
I am trying to create a loop that will copy all of the rows that has a match in one of the columns.
So, if 8 columns, each row with matching value in column 7 should copy to a named sheet.
Sub test()
Set MR = Sheets("Main").Range("H1:H1000")
Dim WOLastRow As Long, Iter As Long
For Each cell In MR
If cell.Value = "X" Then
cell.EntireRow.Copy
Sheets("X").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "Y" Then
cell.EntireRow.Copy
Sheets("Y").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "Z" Then
cell.EntireRow.Copy
Sheets("Z").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
If cell.Value = "AB" Then
cell.EntireRow.Copy
Sheets("AB").Range("A" & Rows.Count).End(xlUp).PasteSpecial
End If
Application.CutCopyMode = False
Next
End Sub
I like this because I need to target multiple destination sheets with different criteria but I need all rows that match criteria to copy over.
EDITED CODE IN RESPONSE TO NEW REQUEST:
The code below will copy all of the rows in Sheet Main and paste them into the corresponding worksheets based on the value in Column 7.
Do note: If there is a value in Column 7 that does NOT match to an existing sheet name, the code will throw an error. Modify the code to handle that exception.
Let me know of any additional needed help.
Sub CopyStuff()
Dim wsMain As Worksheet
Dim wsPaste As Worksheet
Dim rngCopy As Range
Dim nLastRow As Long
Dim nPasteRow As Long
Dim rngCell As Range
Dim ws As Worksheet
Const COLUMN_TO_LOOP As Integer = 7
Application.ScreenUpdating = False
Set wsMain = Worksheets("Main")
nLastRow = wsMain.Cells(Rows.Count, 1).End(xlUp).Row
Set rngCopy = wsMain.Range("A2:H" & nLastRow)
For Each ws In ActiveWorkbook.Worksheets
If UCase(ws.Name) = "MAIN" Then
'Do Nothing for now
Else
Intersect(ws.UsedRange, ws.Columns("A:H")).ClearContents
End If
Next ws
For Each rngCell In Intersect(rngCopy, Columns(COLUMN_TO_LOOP))
On Error Resume Next
Set wsPaste = Worksheets(rngCell.Value)
On Error GoTo 0
If wsPaste Is Nothing Then
MsgBox ("Sheet name: " & rngCell.Value & " does not exist")
Else
nPasteRow = wsPaste.Cells(Rows.Count, 1).End(xlUp).Row + 1
wsMain.Range("A" & rngCell.Row).Resize(, 8).Copy wsPaste.Cells(nPasteRow, 1)
End If
Set wsPaste = Nothing
Next rngCell
Application.ScreenUpdating = True
End Sub
Your current code is pasting to the same row in each sheet over and over, to the last row with a value in column A. Range("A" & Rows.Count).End(xlUp) says, roughly "go to the very bottom of the spreadsheet in column A, and then jump up from there to the next lowest cell in column A with contents," which gets you back to the same cell each time.
Instead, you could use lines of the pattern:
Sheets("X").Range("A" & Sheets("X").UsedRange.Rows.Count + 1).PasteSpecial
Where UsedRange is a range containing all of the cells on the sheet with data in them. The + 1 puts you on the following row.
You could make this a little prettier using With:
With Sheets("X")
.Range("A" & .UsedRange.Rows.Count + 1).PasteSpecial
End With