VBA partly copy from workbook x to workbook y - vba

I'm really bad at VBA (kind of understand when reading the code, but I cannot write it myself).
I would like to create a report file in workbook y that copies part of the data present in workbook x.
I based my current code on the two following articles: Copy from one workbook and paste into another
and Copy value & offset from workbook X to workbook Y only when range value > 0, then loop for remaining rows
I get no error messages with my code, but it doesn't do anything (except open the files). I double-checked the values and the Like, and they seem ok to me.
Any Idea why it doesn't work?
Changed my names & path for anonymity, but here it is:
Private Sub CommandButton1_Click()
Dim x As Workbook
Dim y As Workbook
Dim i, LastRow
'## Open both workbooks first:
Set x = Workbooks.Open("C:\filedestination\filex.xlsx")
Set y = Workbooks.Open("C:\filedestination\filey.xlsm")
'Now, copy what I want from x to y:
LastRow = x.Sheets("Sheetname1").Range("A" & Rows.Count).End(xlUp).Row
y.Sheets("Sheetname2").Range("A2:N5000").ClearContents
For i = 2 To LastRow
If x.Sheets("Sheetname1").Cells(i, "D").Value = "Fixedtext" And x.Sheets("Sheetname1").Cells(i, "F").Value Like "*Subject ?ompensation" Then
x.Sheets("Sheetname1").Cells(i, "D").EntireRow.Copy Destination:=y.Sheets("Sheetname2").Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next i
'Close x:
x.Close
End Sub
Thanks

Two things can be wrong:
LastRow can be 1, thus it does not enter the loop.
Possibly it does not enter in the if clause.
Use the following code to find out which is wrong:
Private Sub CommandButton1_Click()
Dim x As Workbook
Dim y As Workbook
Dim i As Long, LastRow as Long
'## Open both workbooks first:
Set x = Workbooks.Open("C:\filedestination\filex.xlsx")
Set y = Workbooks.Open("C:\filedestination\filey.xlsm")
'Now, copy what I want from x to y:
LastRow = x.Sheets("Sheetname1").Range("A" & Rows.Count).End(xlUp).Row
debug.print LastRow
y.Sheets("Sheetname2").Range("A2:N5000").ClearContents
For i = 2 To LastRow
If x.Sheets("Sheetname1").Cells(i, "D").Value = "Fixedtext" And x.Sheets("Sheetname1").Cells(i, "F").Value Like "*Subject ?ompensation" Then
Debug.Print "Entered in the if"
x.Sheets("Sheetname1").Cells(i, "D").EntireRow.Copy Destination:=y.Sheets("Sheetname2").Range("A" & Rows.Count).End(xlUp).Offset(1)
else
Debug.Print "Did not enter for " ;i
End If
Next i
'Close x:
x.Close
End Sub

Related

How can I use LastRow on a range function?

So I want to copy values from a certain range of cells from worksheet 1-workbook A to worksheet 1- workbook B .
I want to copy everything from the source worksheet: more specifically, every cell that has a value on it.
On the destination worksheet, there are specified cells for the values on source worksheet.
this is my code so far (it's bad, but i'm a noob at VBA!) :
Sub CopyRangeofCells()
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open("C:\test\template.xlsx")
Set y = Workbooks.Open("C:\test\finalfile.xlsx")
x.Sheets("RDBMergeSheet").Range("A1").Copy
y.Sheets("CW Fast").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
On my range, I want to do something like Range("A1:LastRow") or anything of the sort. How do I do it? Can I create a lastrow variable and then do ("A1:mylastrowvariable") ??
Hope you can help! VBA is so confusing to me, give me Java all day long! :P
Let's do it step-by-step:
Sub CopyRangeofCells()
Dim x As Workbook
Dim y As Workbook
Dim LastRow As Long
Set x = Workbooks.Open("C:\test\template.xlsx")
Set y = Workbooks.Open("C:\test\finalfile.xlsx")
With x.Sheets("RDBMergeSheet")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"
.Range("A1:A" & LastRow).Copy
End With
y.Sheets("CW Fast").Range("A1").PasteSpecial xlPasteValues
'Close x:
x.Close
End Sub
Something like this:
Sub CopyRangeofCells()
Dim x As Workbook
Dim y As Workbook
Dim LastRow as Long
Dim LastRowToCopy as Long
Set x = Workbooks.Open("C:\test\template.xlsx")
Set y = Workbooks.Open("C:\test\finalfile.xlsx")
LastRowToCopy = x.Sheets("RDBMergeSheet").Cells(x.Sheets("RDBMergeSheet").Rows.Count, "A").End(xlUp).Row
x.Sheets("RDBMergeSheet").Range("A1:A" & LastRowToCopy).Copy
'copy from A1 to lastrow
LastRow = y.Sheets("CW Fast").Cells(y.Sheets("CW Fast").Rows.Count, "A").End(xlUp).Row + 1 'find the last row
y.Sheets("CW Fast").Range("A" & LastRow).PasteSpecial xlPasteValues
'paste on the lastrow of destination + 1 (so next empty row)
x.Close
End Sub

VLOOKUP to compare data in 2 different workbooks with VBA

I am somewhat new to VBA/Excel, so I was wondering if someone would help me out.
My question:
I have two different workbooks but in these workbooks two of the columns have common data. Thus I wanted to use VLOOKUP to compare the two columns and see if there are common data.
Details:
1st workbook : has 3 different sheets, I only need to use the sheet "Items" which has the data in column 2.
2nd workbook: has only 1 sheet called "Data" and has data in column 4.
Thus my goal is to compare the 2 columns. In workbook1 there is an empty column next to the data column so, if there is a match I want to say "ok" in it. If no match then "".
I tried VLOOKUP but really could not understand it. Plus this is for work.
You may try this..
Assuming the name of your second workbook is Book2.xlsx, then try this...
On First workbook
In C2
=IF(ISNUMBER(MATCH(B2,'[Book2.xlsx]Data'!$D:$D,0)),"OK","")
and copy it down.
If you require a VBA solution, one approach to get the desired output is as below...
The following code assumes that both the Book1.xlsm (which will contain the below code) and Book2.xlsx are saved in the same folder.
If they are saved at different location, change the path and name of Book2.xlsx in the following lines of code.
sourceFilePath = dwb.Path & "\"
sourceFileName = "Book2.xlsx"
Code:
Sub CompareData()
Dim swb As Workbook, dwb As Workbook
Dim sws As Worksheet, dws As Worksheet
Dim slr As Long, dlr As Long, i As Long
Dim sourceFilePath As String, sourceFileName As String
Dim x, y, z, dict
Application.ScreenUpdating = False
Set dwb = ThisWorkbook
Set dws = dwb.Sheets("Items")
dlr = dws.Cells(Rows.Count, 2).End(xlUp).Row
x = dws.Range("B2:B" & dlr).Value
ReDim z(1 To dlr)
sourceFilePath = dwb.Path & "\"
sourceFileName = "Book2.xlsx"
Workbooks.Open sourceFilePath & sourceFileName
Set swb = ActiveWorkbook
Set sws = swb.Sheets("Data")
slr = sws.Cells(Rows.Count, 4).End(xlUp).Row
y = sws.Range("D2:D" & slr).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(y, 1)
dict.Item(y(i, 1)) = ""
Next i
swb.Close False
For i = 1 To UBound(x, 1)
If dict.exists(x(i, 1)) Then
z(i) = "OK"
Else
z(i) = ""
End If
Next i
dws.Range("C2").Resize(UBound(x, 1), 1).Value = Application.Transpose(z)
Application.ScreenUpdating = True
End Sub

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

How to keep record of cell changing in vba

Program Description I want this program to msgbox every time when cell is changing. For ex. If i have AAA in row1 and row2 BBB i want my code to recognize when cell is changing from one string to another string.
Problem I never used change function before so i don't know where to use it in my code. Can anyone help me out with how to use change function or any other ways to keep track of string changing. Somehow my change function not working.
Sub xym()
Dim x As String, dtext, lastrow As Long, ws1 As Worksheet, wb As Workbook
Dim rangnum As Range, i As Long
Set wb = ActiveWorkbook
Set ws1 = wb.Worksheets("Sheet1")
lastrow = ws1.UsedRange.Rows.Count + 1
Set rangenum = ws1.Range("A1:A" & lastrow)
dtext = rangenum.Value
For i = 1 To UBound(dtext, 1)
If dtext(i,1).change then msgbox "yes"
Next i
End Sub
Please try this:
Sub xym()
Dim i&, v
With Sheet1.[a1]
v = .Resize(.Item(.Parent.Rows.Count).End(xlUp)(2).Row)
End With
For i = 2 To UBound(v) - 1
If v(i, 1) <> v(i - 1, 1) Then
MsgBox "Yes." & vbLf & "Cell A" & i & " is different."
End If
Next
End Sub
You need to use the Worksheet Change Event - there is a clear explanation of how to use this event on the following page, including how to only respond to changes that happen in certain cells.
Excel VBA: Automatically Run Excel Macros When a Cell Changes/Enter Data. Worksheet Change Event
http://www.ozgrid.com/VBA/run-macros-change.htm

Using VBA - Insert VLOOKUP depending on certain values

I am trying to retrieve data from another file using the VLOOKUP function however this is only to happen depending on if any of the 3 items of data appear in column 8(H)
OLY
OLY - QUO
OLY - PRO
I have the following and know this is not correct
Sub BlockAllocationsVlookupAll()
Dim x As Long
For x = 1 To 65536
If InStr(1, Sheet1.Range("$H$" & x), "OLY") > 0 Then
Sheet1.Range("$I$" & x) = Sheet1.Range("$I$" & x) & "sometext"
End If
Next
End Sub
I know the above doesn't do exactly what I need can anyone help as to what needs to be edited to include the Vlookup below
=VLOOKUP(A21,'[001 - Allocations - Blocks.xls]CurrentDayAll'!$1:$65536,9,FALSE)
The other issue is that the cell the VLOOKUP points to first will also change due to the varying length of the report
Thank you for any help given
UPD:
As follows up from comments,
column H is in Allocations.xls workbook
there are a set of criterias
formula should be placed in cell only if corresponding cell in column H matches any of thouse criterias.
Working code:
Sub BlockAllocationsVlookupAll()
Dim x As Long
Dim lastrow As Long
Dim searchCriterias As String
Dim wb As Workbook
Dim ws As Worksheet
'specify correct path to your workbook
Set wb = Workbooks.Open("C:\Allocations.xls")
'If workbook is already opened use next line
'Set wb = Workbooks("Allocations.xls")
Set ws = wb.Worksheets("Current Day")
searchCriterias = "|OLY|SVC|SVC-PRO|SVC-QUO|EUR|EUR-PRO|EUR-QUO|"
With ws
lastrow = .Cells(.Rows.Count, "H").End(xlUp).Row
For x = 4 To lastrow
If InStr(1, searchCriterias, "|" & .Range("H" & x) & "|") > 0 Then
.Range("I" & x).Formula = "=VLOOKUP(A" & x & ",'[001 - Allocations - Blocks.xls]CurrentDayAll'!$A:$I,9,FALSE)"
End If
Next
End With
'Comment next line if you don't want to close wb
wb.Close (True)
Set wb = Nothing
End Sub