Determine Range/Conditions for Copy/Paste Procedure - vba

I need help defining my copy/paste process. I just need an example for the two conditions. The situation is as follows:
I need to search for for specific keywords in a sheet of wb1 and
copy/paste it to wb2 under certain conditions.
I dont know the specific sheet or the position of the keywords, so
every sheet in the wb should be checked
In case a keyword is found - condition 1 or condition 2 will be
applied, depending on the keyword:
Condition 1: if keyword in wb1 = "mx1" then copy/paste keyword to wb2
(specific position -> Sheet2, K7) and rename it to "Male". Result
would be: "Male" in K7 of Sheet2 in wb2.
Condition 2: if keyword in wb1 = "Data 1" then copy the
value(integer) of the adjoining cell to the right of it and paste to
wb2 (specific position -> Sheet3, K3). Result would be: "189" in K7
of Sheet3 in wb2.
A keyword can only have one of the conditions assigned.
Actually, my goal is to have a set of keywords, which have condition
1 or condition 2 assigned, as well as a specific paste-location in
wb2. So, every sheet should be checked according to the set of
keywords.
Example:
https://imgur.com/a/8VCNsrC
Would appreciate any help!
Code so far - only thing I need is condition 1 and 2....
Public Sub TransferFile(TemplateFile As String, SourceFile As String)
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(SourceFile) 'open source
Dim rFnd As Range
Dim r1st As Range
Dim ws As Worksheet
Dim arr(1 To 2) As Variant
Dim i As Long
Dim wbTemplate As Workbook
Dim NewWbName As String
Dim wsSource As Worksheet
For Each wsSource In wbSource.Worksheets 'loop through all worksheets in source workbook
Set wbTemplate = Workbooks.Open(TemplateFile) 'open new template
'/* Definition of the value range */
arr(1) = "mx1"
arr(2) = "Data 1"
For i = LBound(arr) To UBound(arr)
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name
Set rFnd = ws.UsedRange.Find(what:=arr(i), LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlRows, _
SearchDirection:=xlNext, MatchCase:=False)
If Not rFnd Is Nothing Then
Set r1st = rFnd
Do
If i = 1 Then
wb2.Sheets("Sheet1").Range("A3").Value = "Male"
Else
wb2.Sheets("Sheet1").Range("B3").Value = rFnd.Offset(0, 1).Value
End If
Set rFnd = ws.UsedRange.FindNext(rFnd)
Loop Until r1st.Address = rFnd.Address
End If
Next
Next
NewWbName = Left(wbSource.Name, InStr(wbSource.Name, ".") - 1)
wbTemplate.SaveAs wbSource.Path & Application.PathSeparator & NewWbName & "_New.xlsx"
wbTemplate.Close False 'close template
Next wsSource
wbSource.Close False 'close source
End Sub

You can search a Range for a value, and a range applies to a (part of a) single sheet. So you need to search each worksheet separately. Similarly, you search for a single value, so in this case you need to issue 2 separate searches. I'd do it this way:
Dim rFnd As Range
Dim r1st As Range
Dim ws As Worksheet
Dim arr(1 to 2) As Variant
Dim i as Long
arr(1) = "mx1"
arr(2) = "Data 1"
For i = Lbound(arr) to Ubound(arr)
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name
Set rFnd = ws.UsedRange.Find(what:=arr(i), LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlRows, _
SearchDirection:=xlNext, MatchCase:=False)
If Not rFnd Is Nothing Then
Set r1st = rFnd
Do
If i = 1 then
wb2.Sheets("Sheet2").Range("K7").Value = "Male"
Else
wb2.Sheets("Sheet3").Range("K3").Value = rFnd.Offset(0, 1).Value
End If
Set rFnd = ws.UsedRange.FindNext(rFnd)
Loop Until r1st.Address = rFnd.Address
End If
Next
Next

Related

Copying data based on cell value

I am a bit stuck and hoping to find some help. I have some experience in VBA but this particular problem exceeds my programming knowledge.
I have a sheet with 1000 - 1250 rows of data, and anywhere from 20 - 60 columns that can change monthly.
What I am hoping to do is look at each cell for an X, and when found it will create a new line on a separate tab. The line would contain the first cell in the row where the X was found and the column header from the column the X was found in.
I have been able to write some things that will find the X's in the sheet, create new items on another page and the like, but I can't get one script to do everything I need.
This is an example of the data structure:
Data
Expected result:
Output
Sorry for the links, I am too new to post photos.
Any help on how this can be achieved, documents, tips or the like would be super helpful and most appreciated. Thank you for looking!
Andrew
EDIT:
Some of the code I have put together:
Dim uSht As String
Dim wsExists As Boolean
Dim lRow As Long
Dim lcol As Long
Dim ws As Worksheet
Sub CopyData()
'Setup Sheetnames
uSht = "UPLOAD"
uTem = "TEMPLATE"
' Stop flicker
Application.ScreenUpdating = False
' Check for Upload Worksheet
WorksheetExists (uSht)
'MsgBox (wsExists)
If wsExists = False Then
' If it does not exist, create it
Call CreateSheet("UPLOAD")
End If
'Setup stuff
Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets(uTem)
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets(uSht)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lcol = Cells(1, Columns.Count).End(xlToLeft).Column
'MsgBox (lRow)
'MsgBox (lCol)
Range(Cells(lRow, lColumn)).Select
Application.ScreenUpdating = True
End Sub
Sub CreateSheet(wsName)
'Creates the uSht worksheet
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = uSht
End With
End Sub
Function WorksheetExists(wsName As String) As Boolean
'Check to see if uSht exists and return.
wsName = UCase(wsName)
For Each ws In ThisWorkbook.Sheets
If UCase(ws.Name) = wsName Then
wsExists = True
Exit For
End If
Next
WorksheetExists = wsExists
End Function
Using FindAll from here: Extracting specific cells from multiple Excel files and compile it into one Excel file
(but change LookAt:=xlPart to LookAt:=xlWhole)
Rough outline:
Dim col, c, dest As Range
Set dest = sheets("results").Range("A2")
Set col = FindAll(sheets("data").range("a1").currentregion, "X")
For each c in col
dest.resize(1,2).value = array(c.entirerow.cells(1).value, _
c.entirecolumn.cells(1).value)
set dest = dest.offset(1, 0)
next
You need a Find/FindNext loop that will locate all X values in the first worksheet. After a found cell is located, the cell's row and column can be used to identify the location and project.
Option Explicit
Sub Macro1()
Dim addr As String, loc As String, pro As String
Dim ws2 As Worksheet, fnd As Range
Set ws2 = Worksheets("sheet2")
With Worksheets("sheet1")
Set fnd = .Cells.Find(What:="x", after:=.Cells(1, 1), _
LookIn:=xlFormulas, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not fnd Is Nothing Then
addr = fnd.Address(0, 0)
Do
loc = .Cells(fnd.Row, "A").Value
pro = .Cells(1, fnd.Column).Value
With ws2
.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0) = loc
.Cells(.Rows.Count, "A").End(xlUp).Offset(0, 1) = pro
End With
Set fnd = .Cells.FindNext(after:=fnd)
Loop Until addr = fnd.Address(0, 0)
End If
End With
End Sub

Comparing Two Workbooks and Deleting Matched Rows

I am trying to compare two workbooks but unlikely upon Running the Macro, getting Error
"Subscript Out of the Range".
Can anyone please help in Removing the Error? Thanks
Sub CompInTwoWorkbooks()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim c As Range, rng As Range
Dim lnLastRow1 As Long, lnLastRow2 As Long
Dim lnTopRow1 As Long, lnTopRow2 As Long
Dim lnCols As Long, i As Long
Set wb1 = Workbooks("listeappli.xlsx") 'Adjust as required
Set wb2 = Workbooks("Keyword.xlsx") 'Adjust as required
Set ws1 = wb1.Sheets("listeappli") 'Adjust as required
Set ws2 = wb2.Sheets("Keyword") 'Adjust as required
lnTopRow1 = 2 'first row containing data in wb1 'Adjust as required
lnTopRow2 = 2 'first row containing data in wb2 'Adjust as required
'Find last cells containing data:
lnLastRow1 = ws1.Range("M:M").Find("*", Range("M1"), LookIn:=xlValues, searchdirection:=xlPrevious).Row
lnLastRow2 = ws2.Range("A:A").Find("*", Range("A1"), LookIn:=xlValues, searchdirection:=xlPrevious).Row
Set rng = ws2.Range("A" & lnTopRow2 & ":A" & lnLastRow2)
lnCols = ws1.Columns.Count
ws1.Columns(lnCols).Clear 'Using the very right-hand column of the sheet
For i = lnLastRow1 To lnTopRow1 Step -1
For Each c In rng
If ws1.Range("M" & i).Value = c.Value Then
ws1.Cells(i, lnCols).Value = "KEEP" 'Add tag to right-hand column of sheet if match found
Exit For
End If
Next c
Next i
'Delete rows where the right-hand column of the sheet is blank
Set rng = ws1.Range(Cells(lnTopRow1, lnCols), Cells(lnLastRow1, lnCols))
rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
ws1.Columns(lnCols).Clear
End Sub
If your workbook is not open already and you want the macro to open it automatically you must use the Workbooks.Open Method.
use the following if listeappli.xlsx is in the same path as the actual file
Set wb1 = Workbooks.Open(Filename:=ThisWorkbook.Path & Application.PathSeparator & "listeappli.xlsx")
or specify the full path for Filename:= like
Set wb1 = Workbooks.Open(Filename:="C:\MyFolder\listeappli.xlsx")

how to match one sheet column data with another sheet?

i have 2 workbook and i want to match workbook-1 sheet one column with another workbook-2 sheet one column,if 2 cell is same match ID then return header.
For example:
i want to return the Workbook-2 Header such as like A001 if my "X" marked ID all is match with workbook-1 ID.
The expected outcome like the "Output" Sheet in workbook-2
Workbook-1
workbook-2
outcome example
I took a stab at this even though it doesn't make much sense to me. It requires that the three sheets you're using use the exact sheet names in the screenshot and no other sheets share the name. I didn't test it but
Sub WhatTheHeckisThis()
Dim WKBK As Workbook, wsStart As Worksheet, wsLookup As Worksheet, wsOutput As Worksheet
Dim lineLookup As Range, i As Long, yCell As Range, rCell As Range
Dim tWSstart As String: tWSstart = "Datasheet"
Dim tWSLookup As String: tWSLookup = "MATCH"
Dim twsOutput As String: twsOutput = "OUTPUT"
For Each WKBK In Application.Workbooks
For Each WS In WKBK.Sheets
If UCase(WS.Name) = UCase(tWSstart) Then
Set wsStart = WS
ElseIf UCase(WS.Name) = (tWSLookup) Then
Set wsLookup = WS
ElseIf UCase(WS.Name) = UCase(twsOutput) Then
Set wsOutput = WS
End If
Next WS
Next WKBK
For Each rCell In Intersect(wsStart.Range("B2:B" & Rows.Count), wsStart.UsedRange).Cells
Set lineLookup = Nothing
Set lineLookup = wsLookup.Cells.Find(rCell.Value, _
After:=wsLookup.Cells.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not lineLookup Is Nothing Then
For Each yCell In Intersect(lineLookup.EntireRow, wsLookup.UsedRange).Cells
If UCase(yCell.Value) = "X" Then
With wsOutput
i = .Cells(Rows.Count, 1).End(xlUp).Row + 1
.Cells(i, 1).Value = i - 1
.Cells(i, 2).Value = wsLookup.Cells(1, yCell.Column).Value
End With
End If
Next yCell
End If
Next rCell
End Sub

Search for specific string format using VBA and paste to a new excel worksheet

I am attempting to consolidate some data into a specific excel template I have created. My data is titled as PAxxx.xx where x could be any number between 0-9. Is there a way I can search through my current workbook for that specific title "PAxxx.xx" and populate it into my created template field.
I current have this search function in VBA:
Sub CopyPasteCellData()
Dim FirstAddress As String
Dim searchTerms As Variant
Dim Rcount As Long
Dim I As Long
Dim Rng As Range
Dim currentWorkbook As Workbook
Dim newWorkbook As Workbook
Dim currentWorksheet As Worksheet
Dim newWorksheet As Worksheet
Set currentWorkbook = Workbooks("LVX Release 2015 (2).xlsm")
Set currentWorksheet = currentWorkbook.Sheets("PA5179.01")
Set newWorkbook = Workbooks("Test.xlsx")
Set newWorksheet = newWorkbook.Sheets("Sheet1")
'newWorksheet.Range("C2").Value = currentWorksheet.Range("A1").Value
searchTerms = Array("PA")
With currentWorksheet.UsedRange
Rcount = 0
For I = LBound(searchTerms) To UBound(searchTerms)
Set Rng = .Find(What:=searchTerms(I), _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
Rcount = Rcount + 1
newWorksheet.Range("A" & Rcount).Value = Rng.Value
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next I
End With
End Sub
Just not sure how to search the sheet for all data sets PAxxx.xx.
Thanks in advance :)
Here is a basic principle how to loop through all the sheets and find for a PAxxx.xx -> read instructions of Like operator if you need to change the validation ->
Sub LoopTroughWorkSheetsAndFindPA()
Dim wb As Workbook: Set wb = ThisWorkbook 'anyreference of a workbook you want
Dim ws As Worksheet
For Each ws In wb.Worksheets
If ws.Name Like "PA###.##" Then
'do some operations here for example ->
Debug.Print ws.Name
End If
Next
End Sub

VBA code to complement search keyword on worksheet with copy rows selected to new worksheet

The code below basically searches for any keyword in any sheet and highlights it. My question is, how to also copy the entire row number where the word/words is/are found to a new sheet in addition to the highlight?
Is it also possible to precise in which worksheet the search will be done?
Many thanks in advance,
Gonzalo
Sub CheckMULTIVALUE()
'This macro searches the entire workbook for any cells containing the text "#MULTIVALUE" and if found _
highlight the cell(s) in yellow. Once the process has completed a message box will appear confirming completion.
Dim i As Long
Dim Fnd As String
Dim fCell As Range
Dim ws As Worksheet
Application.ScreenUpdating = False
Fnd = InputBox("Find what:", "Find and Highlight", "#MULTIVALUE")
If Fnd = "" Then Exit Sub
For Each ws In Worksheets
With ws
Set fCell = .Range("A1")
For i = 1 To WorksheetFunction.CountIf(.Cells, Fnd)
Set fCell = .Cells.Find(What:=Fnd, After:=fCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False)
If fCell Is Nothing Then
MsgBox Fnd & " not on sheet !!"
Exit For
Else
With fCell
.Interior.ColorIndex = 6
End With
End If
Next i
End With
Next ws
Application.ScreenUpdating = True
MsgBox "Check complete"
End Sub
Add code before the For loop to create the results worksheet or clear it if it already exists:
Dim results As Worksheet: Set results = ActiveWorkbook.Sheets("Results")
If results Is Nothing Then
Set results = ActiveWorkbook.Sheets.Add()
results.Name = "Results"
Else
results.Cells.Clear
End If
Create a reference to its A1 cell and a counter:
Dim resultsRange As Range: Set resultsRange = results.Range("A1")
Dim matches As Long
When you find a match add what you need to the Results worksheet and increment the counter.
With fCell
.Interior.ColorIndex = 6
resultsRange.Offset(matches, 0).Value = fCell.Row
resultsRange.Offset(matches, 1).Value = fCell.Value
matches = matches + 1
End With
To specify a specific sheet remove For Each ws In Worksheets and Next ws and replace With ws with With ActiveWorkbook.Sheets("SheetNameHere")