Copying data to another workbook if condition/criteria is satisfied - vba

sorry if this has been asked here many times. I am a beginner in vba excel, so I only have brief idea of how to begin the code. I am using Excel 2013.
I have 2 different workbooks, main and copy.
Row 1 to 4 will be empty.
Row 5 is meant for header/labeling the information it will be providing for both workbooks.
The "main" workbook will be using columns A to DN to store all the data.
If the cell contains "X" - it will copy column A to P, to the workbook "copy". After which, it will go on to the next row to determine the same thing.
If the cell is empty, it will proceed down to the next row to determine the same thing as well.
The code has to be dynamic as new information will be added every 3 months, such as new rows added or the criteria changing from "X" to empty, or empty to "X".
This is the code I have got as of now.
It works but since there are so many columns to check through, I was advised to do another code for this.
Sub copy()
Dim lr As Long, lr2 As Long, r As Long
lr = Sheets("main").Cells(Rows.Count, "A").End(xlUp).row
lr2 = Sheets("copy").Cells(Rows.Count, "A").End(xlUp).row
For r = lr To 2 Step -1
If range("Q" & r).Value = "X" Then
Rows(r).copy Destination:=Sheets("copy").range("A" & lr2 + 1)
lr2 = Sheets("copy").Cells(Rows.Count, "A").End(xlUp).row
End If
Next r
End Sub

For that you will have to declare two workbook variables and two worksheet variables to hold the source and destination workbooks and worksheets reference in the code.
Tweak the following code as per your requirement.
I have added the comments in the code which will help you to understand the flow of the program.
Further, more error handling can be used to make sure the source and destination sheets are found in source and destination workbook respectively.
If required, you can add the error handling as well.
Option Explicit
Sub CopyDatoToAnotherWorkbook()
Dim srcWB As Workbook, destWB As Workbook 'Variables to hold the source and destination workbook
Dim srcWS As Worksheet, destWS As Worksheet 'Variables to hold the source and destination worksheets
Dim FilePath As String 'Variable to hold the full path of the destination workbook including it's name with extension
Dim lr As Long, lr2 As Long, r As Long
Application.ScreenUpdating = False
Set srcWB = ThisWorkbook 'Setting the source workbook
Set srcWS = srcWB.Sheets("main") 'Setting the source worksheet
'Setting the FilePath of the destination workbook
'The below line assumes that the destination file's name is MyFile.xlsx and it is saved at your desktop. Change the path as per your requirement
FilePath = Environ("UserProfile") & "\Desktop\MyFile.xlsx"
'Cheching if the destination file exists, it yes, proceed with the code else EXIT
If Dir(FilePath) = "" Then
MsgBox "The file " & FilePath & " doesn't exist!", vbCritical, "File Not Found!"
Exit Sub
End If
'Finding the last row used in column A on source worksheet
lr = srcWS.Cells(Rows.Count, "A").End(xlUp).Row
'Opening the destination workbook and setting the source workbook
Set destWB = Workbooks.Open(FilePath)
'Setting the destination worksheet
Set destWS = destWB.Sheets("copy")
'Looping through rows on source worksheets
For r = lr To 2 Step -1
'Finding the first empty row in column A on destination worksheet
lr2 = destWS.Cells(Rows.Count, "A").End(xlUp).Row + 1
If srcWS.Range("Q" & r).Value = "X" Then
srcWS.Rows(r).copy Destination:=destWS.Range("A" & lr2 + 1)
End If
Next r
'Closing the destination workbook
destWB.Close True
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

Related

Copy in VBA info from one data sheet already open to other data sheet from other location

I want to copy dates from a sheet name MasterData which contain macro in a file sheet from other location name Data base .At the end I want to clear info from MasterData sheet and to close sheet Data base.
I run below code but nothing is happening.
Please can advise?
I'm kind new in running VBA code...
Thank you.
Mari
Sub Copy_Paste_Below_Last_Cell()
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
Workbooks.Open Filename:="D:\VBA\Test1\Prices_Database_ For_ Volume.xlsx"
'Set variables for copy and destination sheets
Set wsCopy = Workbooks("MacroMaster file.xlsm").Sheets("MasterData")
Set wsDest = Workbooks("Prices_Database_ For_ Volume.xlsx").Sheets ("DataBase")
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
'Offset property moves down 1 row
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row
wsCopy.Range("A2:AB100" & lCopyLastRow).Copy _
wsDest.Range("A" & lDestLastRow)
'Workbooks("Prices_Database_ For_ Volume.xlsx").Close SaveChanges:=True
'Workbooks("MacroMaster file.xlsm").Worksheets("MasterData").Range ("A2:AB100").ClearContents
End Sub
Hope is more ok now
Here is a modification of your code with out all the variables. It incorporates the last rows into each range.
Workbooks.Open Filename:="D:\VBA\Test1\Prices_Database_ For_ Volume.xlsx"
With ThisWorkbook.Sheets("MasterData")
Range("A2:AB" & Cells(Rows.Count, "A").End(xlUp).Row).Copy _
Destination:=Workbooks("Prices_Database_ For_ Volume.xlsx").Sheets("DataBase").Range("A" & Rows.Count).End(xlUp).Offset(1)
End With

Copy a dynamic set of range in one workbook to another

So I have this code that will open a several csv workbooks (let's call this "Source file") listed in "RefData" sheet then copy its contents to destination file.
I have this code working but I'm not really impressed by how it is coded. I believe there's is much better way.
Private Sub OpenDL()
Dim i As Integer
Dim wrk As Workbook
Dim this As Workbook
lastrow = Sheets("RefData").Cells(Rows.Count, 1).End(xlUp).Row
Set wrk = ThisWorkbook
Sheets("RefData").Select
For i = 1 To lastrow
'open workbook
On Error Resume Next
Sheets(Sheets("RefData").Cells(i, 1).Value).Select
Workbooks.Open Filename:=Application.ActiveWorkbook.Path & "\" & "HistoricalPrices_" & Sheets("RefData").Cells(i, 1).Value & ".csv"
'copy Date, Open, High, Low, Close & Volume
Range("A1:" & Range("F1048576").End(xlUp).Address).Select
Selection.Copy
wrk.Activate
Sheets(Sheets("RefData").Cells(i, 1).Value).Select
Range("A1").Select
ActiveSheet.Paste
'close csv file
Application.DisplayAlerts = False
Workbooks("HistoricalPrices_" & Sheets("RefData").Cells(i, 1).Value & ".csv").Close
Application.DisplayAlerts = True
Next i
End Sub
The way how I code it is something like this:
based from the list in refdata column A, macro will open the source
file. the macro have to select A1 up to F + lastrow.
Screenshot of RefData sheet
Then it will copy it.
next is it will close the source file.
paste it to the destination file, in its correct sheet. Please note
that each item listed in Refdata column have its own sheet.
the macro ends.
My issue here is there an easy way to eliminate the step 2 and 3 where it will manually select the ranges then copy it?
I have an idea, not sure if its possible. it goes something like this:
sourcefile.sheets(sheets("refdata").cells(i,1).value).range("A1:F" & lastrow of the destination file).value **=** destinationfile.activesheets.range("A1:F" & lastrow of the destination file).value
something like:
the value of destination file > Sheet(Refdata).cells(I,1) > Range(A1 to F(x) is equal to the value of the Source File > activesheet > Range A1 to F(x)
where x = last row of the source file?
I'm not sure if this is possible. Any help is appreciated
wsDest.Range("A1:" & Range("F1048576").End(xlUp).Address).value = wsOrgn.Range("A1:" & Range("F1048576").End(xlUp).Address).value
However, you need to declare and set the wsDest (Destination worksheet) and wsOrgn (Origin worksheet). You can start with:
Dim wsDest As Worksheet, wsOrgn As Worksheet
and set the Worksheet based on the flow of the process:
'before you open the source, set the destination first
Set wsDest = wrk.Sheets(Sheets("RefData").Cells(i, 1).value)
'codes
'...
'once the source file opened and active on the sheet.
Set wsOrgn = ActiveSheet
'Transfer info from source to destination sheet
wsDest.Range("A1:" & Range("F1048576").End(xlUp).Address).value = wsOrgn.Range("A1:" & Range("F1048576").End(xlUp).Address).value
Range can be more precise by getting the last row from the origin and use it on both wsDest and wsOrgn.
P.S. Those PSE Stocks tho LOL.

VBA Variable Workbook Reference Runtime-Error 9

I'm trying to do a VlookUp with two seperate workbooks. The main workbook opens the supporting workbook right at the beginning like this:
Public Sub GetFile()
Dim MySourceSheet As Variant, wb As Workbook
'Opens window to choose file from
MySourceSheet = Application.GetOpenFilename(FileFilter:= _
"Excel Files (*.XLS; *.XLSX), *.XLS; *.XLSX", Title:="Select file to
retrieve data from.")
If MySourceSheet = False Then Exit Sub
Set wb = Workbooks.Open(MySourceSheet)
End Sub
Throughout the module I reference the document a few times, and then there is this part were the error occurs.
Private Sub VlookupToBeReviewed()
Dim LastColumn As Long
Workbooks("09_PR Status Custodians.xlsm").Activate 'change name
'inserts new column
With Sheets("Prio_Custodians")
LastColumn = Cells(2, .Columns.Count).End(xlToLeft).Column 'change row! 'defines last column
For i = LastColumn To LastColumn Step -2 'moves two columns to the left
.Columns(i).Insert
.Columns(i).ColumnWidth = 10
Next
End With
'puts in the date
Cells(3, LastColumn).Value = Date
'sets up the variables for the vlookup
Dim rw As Long, col As Range
Dim twb As Workbook
'sets up the workbooks
Set twb = ThisWorkbook
Set col = Workbooks(MySourceSheet).Sheets("Documents to be reviewed").Range("A:B")
'vlookup function
With twb.Sheets("Sheet1")
For rw = 3 To .Cells(Rows.Count, 1).End(xlUp).Row
.Cells(rw, LastColumn) = Application.VLookup(.Cells(rw, 2).Value2, col, 2, False)
Next rw
End With
End Sub
Error:
Set col = Workbooks(MySourceSheet).Sheets("Documents to be reviewed").Range("A:B")
Spits out the
Run-time error '9' (Subscript out of range)
However, when I move my courser over MySourceSheet it shows the correct workbook as defined earlier in the module. If I put the name of the workbook manually with the .xls extension, it works all perfectly fine.I tried looking for an answer all over the web but nothing could quite fix it. I'd very much appreciate some help! :)

Open, rename and run same excel macro on multiple excel files

I have about 50 Excel sheets in one folder, on my MacBook - (/Users/myusername/Desktop/Tidy/folder")
I want to perform the following Macro on them all:
Sub SmartCopy()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, i As Long, j As Long
Set s1 = Sheets("s1")
Set s2 = Sheets("s2")
N = s1.Cells(Rows.Count, "Y").End(xlUp).Row
j = 1
For i = 1 To N
If s1.Cells(i, "Y").Value = "No" Then
Else
s1.Cells(i, "Y").EntireRow.Copy s2.Cells(j, 1)
j = j + 1
End If
Next i
End Sub
I am struggling to get the sheets to open, almost like the filepath won't be recognised, also each sheet is named like this:
business-listing-002-w-site.csv
with one tab:
business-listing-002-w-site.csv
So I also need to either 1) rename the sheet each time 2) have the macro just open the only sheet in the workbook.
I want to copy all data from all workbooks into one master. I did try to add my Macro and adapt this one but just can't get it to run at all.
link to another post
You need to define the workbook (file), not just the sheet(tab).
Dim filePath as String
Dim sheetStart as String
Dim count as Integer
Dim sheetEnd as string
Dim thisSheet as Worksheet
Dim wb1 as Workbook
Dim ws1 as Worksheet
filePath = "/Users/myusername/Desktop/Tidy/folder/"
sheetStart = "business-listing-"
sheetEnd = "-w-site"
Set thisSheet as ThisWorkbook.Worksheets("Sheet1")
For count = 1 to 44 'the range of sheets you have
Set wb1 = Workbooks.Open(filePath & sheetStart & format(count, "000") & sheetEnd & ".csv")
Set ws1 = wb1.Worksheets(sheetStart & format(count, "000") & sheetEnd)
'move the ranges you want from ws1 to thisSheet
wb1.close
next count
each time the code loops, it will change the filename being opened and the sheet that it is looking for.
I assume you either know or can find how to copy a range from ws1 to the next available row of thisSheet based on the original code you provided.
edited with improved code based on comments

Run a remove duplicates code on all worksheets apart from named worksheets

I have the following code which removes rows from 'ACHAL' worksheet where a match is found between column M and Column A of 'Archive' worksheet.
I need to run the same script for all worksheets but, my workbook is made up of several worksheets where the worksheet names will frequently change; so I do not want to add the worksheet names to the code.
Within the workbook I have 2 worksheets that have a constant worksheet name (these will not change) and the code needs to run on all worksheets apart from 'All Data' and 'Archive'.
Is there a way of looping the code so it runs on all worksheets apart from 'All Data' and 'Archive'. The code will need to stop after it has run on the last worksheet.
Sub ArchiveMatch()
Dim LR As Long, i As Long
With Sheets("ACHAL")
LR = .Range("M2:M" & Rows.Count).End(xlUp).Row
For i = LR To 1 Step -1
If IsNumeric(Application.Match(.Range("A" & i).Value, Sheets("Archive").Columns("A"), 0)) Then .Rows(i).Delete
Next i
End With
End Sub
You can loop through all sheets, then check that the current sheet isn't All Data or Archive like so:
Sub ArchiveMatch()
Dim LR As Long, i As Long
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
If sh.Name <> "All Data" And sh.Name <> "Archive" Then
LR = sh.Range("M2:M" & Rows.Count).End(xlUp).Row
For i = LR To 1 Step -1
If IsNumeric(Application.Match(sh.Range("A" & i).Value, Sheets("Archive").Columns("A"), 0)) Then sh.Rows(i).Delete
Next i
End If
Next sh
End Sub
You can loop in all the sheets with this:
Sub Main()
Dim i As Integer
For i = 1 To Sheets.Count
Sheets(i).Activate
Next
End Sub
If you have an exception for one or more sheets, compare with this Sheets(i).Name
Hope it works.