VBA code TO COMPARE two worksheets based on KEY - vba

I am comparing 2 worksheets based on a key and write the results in the new workbook. KEY column is A.
2 workbooks are Todays and yesterdays file.
I need to compare todays file with yesterdays file. Below are my scenarios:
If KEY matches in both the Worksheets and if all the columns of that corresponding KEY matches that is from (B:E) , then in F column the value should be NO CHANGE
If KEY matches in both the Worksheets and if any of the columns does not match corresponding to the KEY (B:E), then F column should have value CHANGED
If KEY does not match then F column should have value NEW RECORD
Below is my code writing logic is overriding my values and they are writing records from my yesterdays file instead if todays file :
'ASSUMPTIONS:
'Data begins in cell A1 of each worksheet
'Data is continuous (does not have blank rows or columns)
'Comparison Key should be in column A of each sheet and should NEVER be blank
Sub CompareArrays()
Dim BookOne As String, BookTwo As String, BookThree As String
Dim WorkbookOne As Workbook, WorkbookTwo As Workbook, WorkbookThree As Workbook
Dim SheetOne As Worksheet, SheetTwo As Worksheet, SheetThree As Worksheet
Dim Keytocompare1 As String
Dim Keytocompare2 As String
Dim Keytocompare3 As String
Dim Keytocompare4 As String
Dim Keytocompare5 As String
Sheet1.Cells.ClearContents
'Select Path for First Workbook
MsgBox "Select Today's Common Customer File"
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "SELECT BOOK ONE"
.Show
BookOne = .SelectedItems(1)
End With
'Select Path for Second Workbook
MsgBox "Select Yesterday's Common Customer File"
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "SELECT BOOK TWO"
.Show
BookTwo = .SelectedItems(1)
End With
'Select Path for Output Workbook
MsgBox "Select Output Common Customer File"
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "SELECT BOOK THREE"
.Show
BookThree = .SelectedItems(1)
End With
Application.Workbooks.Open BookOne
Set SheetOne = ActiveWorkbook.Worksheets("Sheet1") '
Application.Workbooks.Open BookTwo
Set SheetTwo = ActiveWorkbook.Worksheets("Sheet1") '
Application.Workbooks.Open BookThree
Set SheetThree = ActiveWorkbook.Worksheets("Sheet1") '
Windows("Today.xlsx").Activate
Sheets("Sheet1").Select
Range("A1").Select
Do While ActiveCell.Value <> ""
Keytocompare1 = ActiveCell.Value
Keytocompare2 = ActiveCell.Offset(0, 1).Value
Keytocompare3 = ActiveCell.Offset(0, 2).Value
Keytocompare4 = ActiveCell.Offset(0, 3).Value
Keytocompare5 = ActiveCell.Offset(0, 4).Value
Windows("yesterday.xlsx").Activate
Sheets("Sheet1").Select
Range("A1").Select
Do While ActiveCell.Value <> ""
If ActiveCell.Value = Keytocompare1 Then
If ((ActiveCell.Offset(0, 1).Value = Keytocompare2) And (ActiveCell.Offset(0, 2).Value = Keytocompare3) And (ActiveCell.Offset(0, 3).Value = Keytocompare4) And (ActiveCell.Offset(0, 4).Value = Keytocompare5)) Then
Windows("Output.xlsx").Activate
Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.Offset(0, 1).Value = Keytocompare2
ActiveCell.Offset(0, 2).Value = Keytocompare3
ActiveCell.Offset(0, 3).Value = Keytocompare4
ActiveCell.Offset(0, 4).Value = Keytocompare5
ActiveCell.Offset(0, 5).Value = "No Change"
Else
Windows("Output.xlsx").Activate
Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.Offset(0, 1).Value = Keytocompare2
ActiveCell.Offset(0, 2).Value = Keytocompare3
ActiveCell.Offset(0, 3).Value = Keytocompare4
ActiveCell.Offset(0, 4).Value = Keytocompare5
ActiveCell.Offset(0, 5).Value = "Change"
End If
Else
Windows("Output.xlsx").Activate
Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.Offset(0, 1).Value = Keytocompare2
ActiveCell.Offset(0, 2).Value = Keytocompare3
ActiveCell.Offset(0, 3).Value = Keytocompare4
ActiveCell.Offset(0, 4).Value = Keytocompare5
ActiveCell.Offset(0, 5).Value = "New Record"
End If
Windows("Yesterday.xlsx").Activate
Sheets("Sheet1").Select
' Range("A2").Select
ActiveCell.Offset(1, 0).Select
Loop
Windows("Today.xlsx").Activate
Sheets("Sheet1").Select
' Range("A2").Select
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Could you guys help out in correcting this ?

give this a try
'ASSUMPTIONS:
'Data begins in cell A1 of each worksheet
'Data is continuous (does not have blank rows or columns)
'Comparison Key should be in column A of each sheet and should NEVER be blank
Sub CompareArrays()
' Sheet1.Cells.ClearContents ' *********** UNKNOWN SHEET
Dim filePick As FileDialog ' set up filePicker object
Set filePick = Application.FileDialog(msoFileDialogFilePicker)
filePick.AllowMultiSelect = False
MsgBox "Select Today's Common Customer File"
filePick.Title = "SELECT BOOK ONE"
filePick.Show
Dim todayBookName As String
todayBookName = filePick.SelectedItems(1)
MsgBox "Select Yesterday's Common Customer File"
filePick.Title = "SELECT BOOK TWO"
filePick.Show
Dim yesterBookName As String
yesterBookName = filePick.SelectedItems(1)
MsgBox "Select Output Common Customer File"
filePick.Title = "SELECT BOOK THREE"
filePick.Show
Dim outputBookName As String
outputBookName = filePick.SelectedItems(1)
Set filePick = Nothing
Dim todayBook As Workbook
todayBook = Application.Workbooks.Open(todayBookName)
Dim yesterBook As Workbook
yesterBook = Application.Workbooks.Open(yesterBookName)
Dim outputBook As Workbook
outputBook = Application.Workbooks.Open(outputBookName)
' -------------------- process workbooks -----------------
Dim recordStatus As String
Dim yesterCell As Range
Dim outputCell As Range
Dim keyToCompare As Variant
Dim i As Integer
Dim todayCell As Range
Set todayCell = todayBook.Sheets("Sheet1").Range("A1") ' set pointer to cell A1
Do While todayCell.Value <> ""
keyToCompare = todayCell.Resize(1, 6).Value ' copy row of cells ... one extra cell at end
keyToCompare = Application.Transpose(keyToCompare) ' convert to
keyToCompare = Application.Transpose(keyToCompare) ' single dimension array
Set yesterCell = yesterBook.Sheets("Sheet1").Range("A1") ' set pointer to cell A1
Do While yesterCell.Value <> "" ' process all non-blank cells
Set outputCell = outputBook.Sheets("Sheet1").Range("A1") ' set pointer to cell A1
If yesterCell.Value = keyToCompare(1) Then
If ( _
(yesterCell.Offset(0, 1).Value = keyToCompare(2)) _
And (yesterCell.Offset(0, 2).Value = keyToCompare(3)) _
And (yesterCell.Offset(0, 3).Value = keyToCompare(4)) _
And (yesterCell.Offset(0, 4).Value = keyToCompare(5))) Then
recordStatus = "No Change"
Else
recordStatus = "Change"
End If
Else
recordStatus = "New Record"
End If
keyToCompare(6) = recordStatus
For i = 1 To 5 ' update 5 cells in output workbook
outputCell.Offset(0, i).Value = keyToCompare(i + 1)
Next i
Set yesterCell = yesterCell.Offset(1, 0) ' move pointer one cell down
Set outputCell = outputCell.Offset(1, 0) ' this is missing from original code
Loop
Set todayCell = todayCell.Offset(1, 0)
Loop
End Sub

I put together a sample VBA code (tested also) assuming all 3 sheets are in current workbook. You can make necessary changes and adjustments to set to your workbooks and worksheets. I have used combination of Excel Formulas and 2 dimensional Arrays to read data from Excel and write back to Excel. Keep in mind, when you read from Excel into 2-d array, lower bound of array is 1, but when you write back to Excel you would need to initiate 0 based array (both for rows and columns).
Public Sub CompareSheets()
Dim wb As Workbook, xlRng As Range
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim Ar1, Ar2, Ar3, ArLoad()
Dim lstR1!, lstR2!, iRow!, nRow!, str1$, str2$
Set wb = ThisWorkbook
Set ws1 = wb.Sheets(1): Set ws2 = wb.Sheets(2): Set ws3 = wb.Sheets(3)
' Get the last non blank cell in Column A in 1st and 2nd worksheets
Set xlRng = ws3.Cells(1, 1)
With xlRng
.FormulaR1C1 = "=MAX((" & ws1.Name & "!C1<>"""")*(ROW(" & ws1.Name & "!C1)))"
.FormulaArray = .Formula: .Calculate: lstR1 = .Value2
.FormulaR1C1 = "=MAX((" & ws2.Name & "!C1<>"""")*(ROW(" & ws2.Name & "!C1)))"
.FormulaArray = .Formula: .Calculate: lstR2 = .Value2
.Clear
End With
' Load into 2-d array data 1st and 2nd sheets
Ar1 = ws1.Range("A1:E" & lstR1).Value
Ar2 = ws2.Range("A1:E" & lstR2).Value
' Load Row number of 1st sheet that matches current row of second sheet
Set xlRng = ws3.Range("A1:A" & lstR2)
With xlRng
.FormulaR1C1 = "=IFERROR(MATCH(" & ws2.Name & "!RC," & ws1.Name & "!C,0),0)"
.Calculate: Ar3 = .Value: .Clear
End With
ReDim Preserve ArLoad(lstR2 - 1, 5) ' this is the array that will be loaded into 3rd worksheet
For iRow = 1 To UBound(Ar3, 1)
For nCol = 1 To 5
ArLoad(iRow - 1, nCol - 1) = Ar2(iRow, nCol) ' Load ArLoad with data from ws2
Next nCol
' Load Last Column of ArLoad with respective value depending if there is a change o
If Ar3(iRow, 1) > 0 Then
nRow = Ar3(iRow, 1) ' matching row number of 1st worksheet
str2 = Ar2(iRow, 2) & Ar2(iRow, 3) & Ar2(iRow, 4) & Ar2(iRow, 5)
str1 = Ar1(nRow, 2) & Ar1(nRow, 3) & Ar1(nRow, 4) & Ar1(nRow, 5)
If str1 = str2 Then
ArLoad(iRow - 1, 5) = "NO CHANGE"
Else
ArLoad(iRow - 1, 5) = "CHANGED"
End If
Else
ArLoad(iRow - 1, 5) = "NEW RECORD"
End If
Next iRow
ws3.Range("A1:F" & lstR2).Value = ArLoad
End Sub

Related

Copy one cell and paste down a column

Been trying to figure out how to copy a cell from worksheet A and paste it down a column in Worksheet B until it matches the same amount of rows as an adjacent column. Take the following screenshot for example. How would I properly accomplish this in VBA? Been trying to figure this out for a while now. All I've been able to do is copy the cell and paste it adjacent to the last cell in the adjacent column instead of down the entire column. The worksheet I'm copying data from is pictured below.
Copy From SpreadSheet down below
Paste to SpreadSheet down below
Current Code
Sub pullSecEquipment()
Dim path As String
Dim ThisWB As String
Dim wbDest As Workbook
Dim shtDest As Worksheet
Dim shtPull As Worksheet
Dim Filename As String
Dim Wkb As Workbook
Dim CopyRng As Range, DestRng As Range
Dim lRow As Integer
Dim destLRow As Integer
Dim Lastrow As Long
Dim FirstRow As Long
Dim UpdateDate As String
ThisWB = ActiveWorkbook.Name
Dim selectedFolder
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
selectedFolder = .SelectedItems(1) & "\"
End With
path = selectedFolder
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = Workbooks("GPnewchapterTEST2.xlsm").Worksheets("START")
'clear content of destination table
shtDest.Rows("8:" & Rows.Count).ClearContents
Filename = Dir(path & "\*.xls*", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
'MsgBox Filename
'''''
'SEC
'''''
If InStr(Filename, "Equipment") <> 0 Then
Dim range1 As Range
Set range1 = Range("E:K")
'For Each Wkb In Application.Workbooks
'For Each shtDest In Wkb.Worksheets
'Set shtPull = Wkb.Sheets(1)
'If shtPull.Name Like "*-*" Then
'last row
destLRow = Wkb.Sheets(1).Cells.Find(what:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
'1st row
lRow = Wkb.Sheets(1).Cells.Find(what:="EQUIPMENT DESCRIPTION", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'STHours
Dim i As Integer
For i = lRow To destLRow
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 5).Address, Cells(i, 11).Address)
Set DestRng = shtDest.Range("O" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row + 1)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 1).Address, Cells(i, 1).Address)
Set DestRng = shtDest.Range("C" & shtDest.Cells(Rows.Count, "O").End(xlDown).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 3).Address, Cells(i, 3).Address)
Set DestRng = shtDest.Range("S" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
i = i + 2
Next i
'Dim cell As Integer
'Dim empname As String
'destLRow = 8 '' find out how to find first available row
'For cell = 2 To lRow
'empname = Wkb.Sheets(1).Cells(cell, 3).Value & " " & Wkb.Sheets(1).Cells(cell, 4).Value
' shtDest.Cells(8, 5).Value = empname
'shtDest.Cells(8, 1).Value = "Service Electric"
'Next cell
' Wkb.Close Save = False
End If
'End If
Filename = Dir()
Loop
MsgBox "Done!"
End Sub
if you want to do in VBA and want to copy one value in "ALL" column
Cells(1,1).Copy Columns(1)

VBA: Copy data from multiple sheets of an excel to one destination file/sheet

I'm trying to copy data from multiple worksheet of a particular excel and paste into the master worksheet. I've written the following code; although it doesn't throw any error, it doesn't go back to the master worksheet ("DestFile" in the code) not does it paste the data. Appreciate any support here.
Sub Monthly_Balance_Fetcher_Click()
Dim DestFile As Workbook, SourceFile As String, GetBook As String, SourceBook As String, myNum As Long, LatestDate As Long, SelectedDate As Long
LatestDate = Range("D1").Value
Set DestFile = ThisWorkbook 'ThisWorkbook is always the workbook that has the code (as opposed to ActiveWorkbook)
GetBook = ActiveWorkbook.Name
SourceFile = Application.GetOpenFilename(Title:="Please browse for the latest monthly TB file, prefer if you save it to your C first")
Workbooks.Open (SourceFile)
SourceBook = ActiveWorkbook.Name
Sheets("Group").Select
myNum = Application.InputBox("Please enter the column number you want to copy from")
Cells(3, myNum).Select
SelectedDate = Cells(3, myNum).Value
If SelectedDate > LatestDate Then
For i = 1 To totalsheets
If Worksheets(i).Name <> "Summary" And Worksheets(i).Name <> "Process Steps" And Worksheets(i).Name <> "Sheet1" And Worksheets(i).Name <> "Adjustments" And Worksheets(i).Name <> "Targets" Then
Worksheets(i).Activate
Range(Cells(6, myNum)).Copy
Range(Cells(13, myNum)).PasteSpecial Paste:=xlPasteValues
DestFile.Activate
lastrow = Cells(Rows.Count, 3).End(xlUp).Row
Cells(lastrow + 1, 3) = Worksheets(i).Name
Range(Cells("G" & lastrow + 1)).PasteSpecial Paste:=xlPasteValues
Cells(lastrow + 1, 8) = SelectedDate
End If
Next
Else
MsgBox "Data from the selected date already exists! This macro will now stop", vbExclamation
DestFile.Activate
Cells(3, 5) = SelectedDate
Cells(2, 4) = LatestDate
End If
End Sub

Statement to create excel vba hyperlink throws Run-time '1004' Error

So I have had a couple of questions I've asked regarding excel VBA, and I appreciate you all bearing with me as I stumble through learning about all this. Your answers have been a tremendous help and learning experience.
So far, I have a subroutine whose main responsibility is to write all of the values collected through a user form with various validations and dynamic comboboxes. My final task is to get this Subroutine to assign a hyperlink to the location selected by an earlier loop. But with my current syntax, I'm getting a "run-time error '1004' method '_default' of object 'range' failed". Some research proved that the cell coordinates require a .address property after them in order to avert this error, but it did not resolve the issue. The code is below:
Option Explicit
Dim cnt As Integer
Dim i As Long, rowOff As Long
Dim dateSel As String
Dim timeSel As String
Dim branch As String
Dim sht As Worksheet
Dim cel As Range
Dim matchingHeader As Range
Public Sub UserForm_Initialize()
'clear form
BranchBox.Value = ""
DateBox.Value = ""
TimeBox.Value = ""
'populate sheet names from each branch
For Each sht In ActiveWorkbook.Sheets
If sht.Name = "ApplicantInfo" Then
'Do Nothing
Else
Me.BranchBox.AddItem sht.Name
End If
Next sht
End Sub
Public Sub HoldButton_Click() 'revisit... throwing Time message box regardless what's selected
If TimeBox.Value <> "" Then
If DateBox.Value <> "" Then
If BranchBox.Value <> "" Then
sht.Cells(rowOff, i).Value = "-"
'Save workbook
Else
MsgBox "You must select a branch for your appointment"
End If
Else
MsgBox "You must select a date for your appointment"
End If
Else
MsgBox "You must select a time for your appointment"
End If
End Sub
Private Sub ResetButton_Click()
FirstName.Value = ""
LastName.Value = ""
EMail.Value = ""
Phone.Value = ""
Skills.Value = ""
'BranchBox.Value = "" throws error
DateBox.Value = ""
TimeBox.Value = ""
End Sub
Private Sub ScheduleButton_Click()
Dim row As Long, column As Long
Dim linkDisplay As String
'test for RowOff and i <> 0
If IsNull(BranchBox) = True Then
MsgBox "Select a branch for you interview before you click schedule"
Else
If IsNull(DateBox) = True Then
MsgBox "Select a date for you interview before you click schedule"
Else
If IsNull(TimeBox) = True Then
MsgBox "Select a time for you interview before you click schedule"
Else
'find first empty row in applicant profile tab.
'Insert applicant information in free row
'parse applicant name as a link to found free row above
'replace "-" placeholder for held appointment with applicant name as a link
Call GetFirstEmptyRow
'write selected values into row
Dim InfoRow As Integer
InfoRow = ActiveCell.row
ActiveCell.Value = ActiveCell.Offset(-5, 0).Value + 5
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = LastName.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = FirstName.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = EMail.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Phone.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Skills.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = BranchBox.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = DateBox.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TimeBox.Value
branch = BranchBox.Value
Set sht = ActiveWorkbook.Worksheets(branch)
dateSel = DateBox.Value
timeSel = TimeBox.Value
'scan for selected date
For i = 2 To sht.Rows.Count
Set cel = sht.Cells(i, 1)
If cel.Value = dateSel Then
column = i
Exit For
End If
Next i
'Scan for selected time
For i = 2 To sht.Columns.Count
Set cel = sht.Cells(1, i)
If CStr(cel.Value) = timeSel Then
row = i
Exit For
End If
Next i
linkDisplay = LastName.Value & ", " & FirstName.Value
'This is the error
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, Address:="", SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo").Cells(InfoRow, 1).Address, TextToDisplay:=linkDisplay
'end of validations
End If
End If
End If
End Sub
Public Sub GetFirstEmptyRow()
Set sht = ActiveWorkbook.Worksheets("ApplicantInfo")
sht.Activate
Range("A1").Select
Do
If IsEmpty(ActiveCell) = False Then
ActiveCell.Offset(1, 0).Select
End If
Loop Until IsEmpty(ActiveCell) = True
End Sub
Public Sub Save()
End Sub
Public Sub TimeBox_Change()
End Sub
Public Sub BranchBox_Change()
'clear Date Box Values
For i = DateBox.ListCount - 1 To 0 Step -1
DateBox.RemoveItem i
Next i
'clear Time Box Values
i = 0
For i = TimeBox.ListCount - 1 To 0 Step -1
TimeBox.RemoveItem i
Next i
'reset i to 0
i = 0
'populate dates
Me.DateBox.List = Worksheets(BranchBox.Value).Range("A2:A31").Value
End Sub
Public Sub DateBox_Change()
branch = BranchBox.Value
Set sht = ActiveWorkbook.Worksheets(branch)
dateSel = DateBox.Value
'Get Row to scan
For i = 2 To sht.Rows.Count
Set cel = sht.Cells(i, 1)
If cel.Value = dateSel Then
rowOff = i
Exit For
End If
Next i
'Scan selected row for blank cells
For i = 2 To sht.Columns.Count
Set cel = sht.Cells(rowOff, i)
If CStr(cel.Value) = "" Then
Set matchingHeader = sht.Cells(1, i)
TimeBox.AddItem matchingHeader.Text
End If
Next i
Me.TimeBox.AddItem ("No Appointments Available")
End Sub
This is the line which errors:
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, _
Address:="", _
SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo") _
.Cells(InfoRow, 1).Address, _
TextToDisplay:=linkDisplay
Help is much appreciated! Thanks in advance!
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column), _
Address:="", _
SubAddress:="'ApplicantInfo'!" & Cells(InfoRow, 1).Address(False, False), _
TextToDisplay:=linkDisplay
I'd typically use a utility method for this type of thing though.
E.g. something like:
Sub CreateHyperlink(FromCell As Range, ToCell As Range, Optional LinkText As String = "")
Dim subAddr, txt
subAddr = ToCell.Address(False, False)
If FromCell.Worksheet.Name <> ToCell.Worksheet.Name Then
subAddr = "'" & ToCell.Worksheet.Name & "'!" & subAddr
End If
txt = IIf(LinkText <> "", LinkText, FromCell.Value)
If Len(txt) = 0 Then txt = "Go"
With FromCell.Worksheet
.Hyperlinks.Add Anchor:=FromCell, Address:="", _
SubAddress:=subAddr, TextToDisplay:=txt
End With
End Sub

Conditional copy Excel File-2 data to excel file-1?

I am using Excel 2007. I try to copy Unit-price from the Excel file-2 data to the Excel file-1 when certain columns data matching from file-1 with file-2.
Thanks for the helps & guidance.
My VBA Code:
Sub mySales()
Dim LastRow As Integer, i As Integer, erow As Integer, Pipe_Class As String, Pipe_Description As String, End_Type As String, Pipe_Size As String
Dim wbk As Workbook
strPriceFile = "C:\Temp\File-2.xlsx"
LastRow = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
Pipe_Class = ""
Pipe_Description = ""
End_Type = ""
Pipe_Size = ""
Pipe_Class = ActiveSheet.Cells(i, 1).Value
Pipe_Description = ActiveSheet.Cells(i, 2).Value
End_Type = ActiveSheet.Cells(i, 3).Value
Pipe_Size = ActiveSheet.Cells(i, 4).Value
Set wbk = Workbooks.Open(strPriceFile)
Worksheets("SOR2").Select
If Cells(i, 1) = Pipe_Class And Cells(i, 2) = Pipe_Description And Cells(i, 3) = End_Type And Cells(i, 4) = Pipe_Size Then
Range(Cells(i, 12), Cells(i, 12)).Select
Selection.Copy
??? After Here how select my current file & paste ????????
Worksheets("SOR1").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 12).Select
ActiveSheet.Paste
ActiveWorkbook.Save
End If
Next i
ActiveWorkbook.Close
Application.CutCopyMode = False
End Sub
I haven't checked all your code, but I have refactored what you have in your question in an attempt to open the Workbook once and to assign proper objects so that you can keep track of what action is being applied to which worksheet.
Sub mySales()
Dim LastRow As Integer, i As Integer, erow As Integer
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim wbDst As Workbook
Dim wsDst As Worksheet
Dim strPriceFile As String
Set wbDst = ActiveWorkbook
Set wsDst = ActiveSheet
strPriceFile = "C:\Temp\File-2.xlsx"
Set wbSrc = Workbooks.Open(strPriceFile)
Set wsSrc = wbSrc.Worksheets("SOR2")
LastRow = wsDst.Range("A" & wsDst.Rows.Count).End(xlUp).Row
erow = LastRow + 1
For i = 2 To LastRow
If wsSrc.Cells(i, 1).Value = wsDst.Cells(i, 1).Value And _
wsSrc.Cells(i, 2).Value = wsDst.Cells(i, 2).Value And _
wsSrc.Cells(i, 3).Value = wsDst.Cells(i, 3).Value And _
wsSrc.Cells(i, 4).Value = wsDst.Cells(i, 4).Value Then
wsSrc.Cells(i, 12).Copy wsDst.Cells(erow, 12)
erow = erow + 1 ' your current code would always copies to the same row,
' but I **think** you probably want to copy to the
' next row each time
End If
Next i
wbSrc.Close
If erow > LastRow + 1 Then
wbDst.Save
End If
wbDst.Close
End Sub
The code is completely untested but, even if it doesn't work, at least it should give you an idea of how you should be processing multiple workbooks and multiple worksheets.

Run-time error on finding last used column

I Have an excel VBA code to merge sheets in workbooks of a folder.First it wants to copy all cells to output sheet from the first sheet.Next sheet onwards, it wants to copy from the 2nd row till last used row.The column headings of input sheets may not be in same order.It is showing an automation error on debugging the below line for finding last used column
**lco = ws2.Cells(1, Columns.Count).End(xlToLeft).Column**
the entire code is following:
Application.ScreenUpdating = False
directory = "C:\Users\Desktop\MYExcel\Input\"
fileName = Dir(directory & "*.xl??")
i = 0
j = 0
'create new output file
Set Wk = Workbooks.Add
With Wk
.Title = "All Sheets"
.SaveAs fileName:="C:\Users\Desktop\MYExcel\Output\AllSheets.xlsx"
.Close
End With
Do While fileName <> ""
If i = 0 Then
Set x = Workbooks.Open(directory & fileName) 'Opening the first workbook in directory
Set y = Workbooks.Open("C:\Users\Desktop\MYExcel\Output\AllSheets.xlsx") 'opening the output workbook
Set ws2 = y.Sheets(1)
If j = 0 Then
Set ws1 = x.Sheets(1)
With ws1
.Cells.Copy ws2.Cells 'Copying all cells to output sheet for s
y.Close True
'x.Close False
End With
j = j + 1
End If
If j > 0 Then
For Each sheet In x.Worksheets
'Set ws2 = y.Sheets(1)
' lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
lci = sheet.Cells(1, Columns.Count).End(xlToLeft).Column
**lco = ws2.Cells(1, Columns.Count).End(xlToLeft).Column**
lri = sheet.Range("A65536").End(xlUp).Row
lro = ws2.Range("A65536").End(xlUp).Row
For Each cell In rng
For Each cell2 In rng2
l = ActiveCell.Column
If cell.Value = cell2.Value Then
With sheet
.Cells(cell, 2).EntireColumn.Copy ws2.Cells(cell2).Range(lro)
End With
End If
Next cell2
Next cell
Next sheet
End If
Workbooks(directory & fileName).Close
fileName = Dir()
i = i + 1
Else
Set d = Workbooks.Open(directory & fileName)
Set f = Workbooks.Open("AllSheets.xls*")
'Windows("Book3.xlsm").Activate
For Each sheet In x.Worksheets
Set ws4 = f.Sheets(1)
lci = sheet.Cells(1, sheet.Columns.Count).End(xlToLeft).Column
lco = ws4.Cells(1, ws4.Columns.Count).End(xlToLeft).Column
lri = sheet.Range("A65536").End(xlUp).Row
lro = ws4.Range("A65536").End(xlUp).Row
Set rng = sheet.Range("A1:A" & lci)
Set rng2 = ws4.Range("A1:A" & lco)
For Each cell In rng
For Each cell2 In rng2
l = ActiveCell.Column
If cell.Value = cell2.Value Then
With sheet
.Cells(cell, 2).EntireColumn.Copy ws4.Cells(cell2).Range(lro)
End With
End If
Next cell2
Next cell
Next sheet
End If
Loop
Code you have used to get LastColumn is absolutely fine. It is working at my end.
Only you need to check that you have commented the line
Set ws2 = y.Sheets(1)
Please uncomment the same and check, it must work.