Loop through range and copy paste between workbooks - excel

I am trying to copy and paste data between two workbooks. I am using a third separate workbook where the user can indicate the copy range, the paste range and indicate if it is a cell or row that is to be copy-pasted. The layout is as follow:
Source Target Cell/Row
G29 G29 Cell
G30 G32 Cell
G31 G33 Row
For example based on the above the VBA code is supposed to copy what is in cell G29 in source workbook and paste it in G29 in target workbook and so on. I have defined the "Source" range as rng and loop through the range in order to define the target range and whether it is a cell or row that is to be copy-pasted. However, for some reason I get an error in first defining my cell_source, cell_target and cell_cellrow variables and also get errors when running the loop where I set the target cell in target workbook equal to the cell_source_input variable. I would much appreciate if anyone can help with this.
Sub transferScript()
Dim wbMain As Workbook: Set wbMain = ThisWorkbook
Dim wbMainDashboard As Worksheet: Set wbMainDashboard = wbMain.Worksheets("Dashboard")
Dim CopyLastRow As Long
Dim rng As Range: Set rng = Application.Range("Dashboard!E9:E15") 'change to E150 !!
sourceModel = wbMainDashboard.Range("FILE_SOURCE")
targetModel = wbMainDashboard.Range("FILE_TARGET")
Dim wbSource As Workbook: Set wbSource = Workbooks.Open(Filename:=sourceModel)
Dim wbTarget As Workbook: Set wbTarget = Workbooks.Open(Filename:=targetModel)
'Source workbook
Dim wsKpInput_source As Worksheet: Set wsKpInput_source = wbSource.Worksheets("INPUT (KP)")
Dim wsSCEInput_source As Worksheet: Set wsSCEInput_source = wbSource.Worksheets("INPUT (SCE)")
'Target workbook
Dim wsKpInput_target As Worksheet: Set wsKpInput_target = wbTarget.Worksheets("INPUT (KP)")
Dim wsSCEInput_target As Worksheet: Set wsSCEInput_target = wbTarget.Worksheets("INPUT (SCE)")
'Error handling
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
Dim i As Integer
Dim cell_source As String
Dim cell_target As String
Dim cell_cellrow As String
Dim cell_source_input As Variant
For i = 0 To rng.Rows.Count
'Definition of source cell, target cell, and cell_row input
cell_source = rng.Cells
cell_target = rng.Cells.Offset(rowOffset:=0, columnOffset:=1)
cell_cellrow = rng.Cells.Offset(rowOffset:=0, columnOffset:=3)
cell_source_input = wsKpInput_source.Range(cell_source)
If cell_cellrow = "Cell" Then
wsKpInput_target.Range(cell_source) = cell_source_input
End If
Next
End Sub

Supposing that there is no mistake on the previous code:
Dim i As Integer
Dim cell_source As String
Dim cell_target As String
Dim cell_cellrow As String
Dim cell_source_input As Variant
For i = 0 To rng.Rows.Count
'Definition of source cell, target cell, and cell_row input
cell_source = rng.Cells
cell_target = rng.Cells.Offset(rowOffset:=0, columnOffset:=1)
cell_cellrow = rng.Cells.Offset(rowOffset:=0, columnOffset:=3)
cell_source_input = wsKpInput_source.Range(cell_source)
If cell_cellrow = "Cell" Then
wsKpInput_target.Range(cell_source) = cell_source_input
End If
Next
Should be:
Dim i As Integer
Dim cell_source As String
Dim cell_cellrow As String
Dim cell_source_input As Variant
For i = 0 To rng.Rows.Count
'Definition of source cell, target cell, and cell_row input
cell_source = rng.Cells(i,1).Value 'It seems to, but it is not clear with no sample
cell_cellrow = rng.Cells(i,1).Offset(0, 3).Value
cell_source_input = wsKpInput_source.Range(cell_source)
If cell_cellrow = "Cell" Then
wsKpInput_target.Range(cell_source) = cell_source_input
End If
Next
Hope it helps... Always be better if you provide some sample of the input and expected output. Anyhow, in the code previous to this procedure there are a few issues: sourceModel is not defined and it seems to be a Range, targetModel is not defined and it seems to be a Range, Workbooks.Open(Filename:=sourceModel) it is trying to open one file with a Filename that it is taking a Range... check them...

Related

How to paste the data in a range where the starting row and column of the range is defined in a cell?

I have two sheets in my excel file:
Input Sheet: Sheet1
Target Sheet: Sheet2
What I want to achieve is to paste the value start from the column that I defined in cell C5 and also start from the row that I defined in cell C6. If the range defined by cell C5 and C6 already have data, then it will find the next empty row based on the column in cell C5 and paste the data in that empty row.
For example in the screenshot above, the starting column & row defined in cell C5 & C6 is B8, so the copied value will be pasted starting from cell B8 until E8. However, if the row already have data, then it will find the next empty row based on column B (which is B9) and paste it there.
I'm not sure how to modified my current script:
Public Sub CopyData()
Dim InputSheet As Worksheet ' set data input sheet
Set InputSheet = ThisWorkbook.Worksheets("Sheet1")
Dim InputRange As Range ' define input range
Set InputRange = InputSheet.Range("G6:J106")
Dim TargetSheet As Worksheet
Set TargetSheet = ThisWorkbook.Worksheets("Sheet2")
Const TargetStartCol As Long = 2 ' start pasting in this column in target sheet
Const PrimaryKeyCol As Long = 1 ' this is the unique primary key in the input range (means first column of B6:G6 is primary key)
Dim InsertRow As Long
InsertRow = TargetSheet.Cells(TargetSheet.Rows.Count, TargetStartCol + PrimaryKeyCol - 1).End(xlUp).Row + 1
' copy values to target row
TargetSheet.Cells(InsertRow, TargetStartCol).Resize(ColumnSize:=InputRange.Columns.Count).Value = InputRange.Value
End Sub
Any help or advice will be greatly appreciated!
Testing Scenario 1
Output of Testing Scenario 1
Please, try the next code:
Public Sub CopyData_()
Dim InputSheet As Worksheet: Set InputSheet = ThisWorkbook.Worksheets("Sheet1")
Dim InputRange As Range: Set InputRange = InputSheet.Range("G6:J106")
Dim arr: arr = InputRange.Value
Dim TargetSheet As Worksheet: Set TargetSheet = ThisWorkbook.Worksheets("Sheet2")
Dim TargetStartCol As String, PrimaryKeyRow As Long
TargetStartCol = TargetSheet.Range("C5").Value ' start pasting in this column in target sheet
PrimaryKeyRow = TargetSheet.Range("C6").Value ' this is the row after the result to be copied
Dim InsertRow As Long
InsertRow = TargetSheet.cells(TargetSheet.rows.Count, TargetStartCol).End(xlUp).row + 1
If InsertRow < PrimaryKeyRow Then InsertRow = PrimaryKeyRow + 1 'in case of no entry after PrimaryKeyRow (neither the label you show: "Row")
' copy values to target row
TargetSheet.cells(InsertRow, TargetStartCol).Resize(UBound(arr), UBound(arr, 2)).Value = arr
End Sub
Not tested, but if should work, I think. If something not clear or going wrong, please do not hesitate to mention the error, what it does/doesn't against you need or anything else, necessary to correct it.
Copy Data to Another Worksheet
Option Explicit
Sub CopyData()
Const sName As String = "Sheet1"
Const rgAddress As String = "G6:J106"
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(sName)
Dim rg As Range: Set rg = ws.Range(rgAddress)
WriteCopyData rg
' or just:
'WriteCopyData ThisWorkbook.Worksheets("Sheet1").Range("G6:J106")
End Sub
Sub WriteCopyData(ByVal SourceRange As Range)
Const dName As String = "Sheet2"
Const dRowAddress As String = "C6"
Const dColumnAddress As String = "C5"
Dim rCount As Long: rCount = SourceRange.Rows.Count
Dim cCount As Long: cCount = SourceRange.Columns.Count
Dim dws As Worksheet
Set dws = SourceRange.Worksheet.Parent.Worksheets(dName)
Dim dRow As Long: dRow = dws.Range(dRowAddress).Value
Dim dCol As String: dCol = dws.Range(dColumnAddress).Value
Dim dfrrg As Range: Set dfrrg = dws.Cells(dRow, dCol).Resize(1, cCount)
Dim dlCell As Range
Set dlCell = dfrrg.Resize(dws.Rows.Count - dRow + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If Not dlCell Is Nothing Then
Set dfrrg = dfrrg.Offset(dlCell.Row - dRow + 1)
End If
Dim drg As Range: Set drg = dfrrg.Resize(rCount)
drg.Value = SourceRange.Value
End Sub

How to paste on each cell while using For each cell loop

I have 2 columns A and B. I created a Sub loop to check if the value of cells in column 2 is <> "NULL" then if its not NULL I have to copy the valueof it and paste it to its counterpart row in Column A.
I tried this code but can't continue because I'm having a hard time pasting the value of the cell in column 2 to its left side column 1 counterpart it only paste in cell A2. How to paste it to every cell in the 1st column if the column 2 counterpart of it is not equal to NULL?
Sub IF_Loop()
Dim cell As Range
For Each cell In Range("TablePrac[Department]")
If cell.Value <> "NULL" Then
cell.Copy Range("A2")
End If
Next cell
End Sub
Copy Values in Excel Table
Before
After
The key difference between the two solutions is that the first 'deals' with the rows and columns of the worksheet, while the second uses the table (DataBodyRange) rows and columns (seems kind of more appropriate).
The 'cValue/CStr business' avoids the type mismatch error occurring if there is an error value.
Adjust the values in the constants section.
The Code
Option Explicit
Sub TableColumns()
Const wsName As String = "Sheet1"
Const dColString As String = "Table1[Column1]"
Const sColString As String = "Table1[Column2]"
Const sCriteria As String = "NULL"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim drg As Range: Set drg = ws.Range(dColString)
drg.ClearContents
Dim dCol As Long: dCol = drg.Column ' Worksheet Column
Dim srg As Range: Set srg = ws.Range(sColString)
Application.ScreenUpdating = False
Dim sCell As Range
Dim cValue As Variant
For Each sCell In srg.Cells
cValue = sCell.Value
If CStr(cValue) <> sCriteria Then
sCell.EntireRow.Columns(dCol).Value = sCell.Value ' Worksheet Row
End If
Next sCell
Application.ScreenUpdating = True
End Sub
Sub TableColumnsRowRange()
Const wsName As String = "Sheet1"
Const tblName As String = "Table1"
Const sColTitle As String = "Column2"
Const sCriteria As String = "NULL"
Const dColTitle As String = "Column1"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim tbl As ListObject: Set tbl = ws.ListObjects(tblName)
Dim sCol As Long: sCol = tbl.ListColumns(sColTitle).Index ' Table Column
Application.ScreenUpdating = False
Dim dCol As Long
With tbl.ListColumns(dColTitle)
.DataBodyRange.ClearContents
dCol = tbl.ListColumns(dColTitle).Index ' Table Column
End With
Dim srrg As Range
Dim cValue As Variant
For Each srrg In tbl.DataBodyRange.Rows ' Table (DataBodyRange) Row
cValue = srrg.Cells(sCol).Value
If CStr(cValue) <> sCriteria Then
srrg.Cells(dCol).Value = srrg.Cells(sCol).Value
End If
Next srrg
Application.ScreenUpdating = True
End Sub

Excel two column of different file comparison and replace next column

Hi I want to compare two excel files and if any strings in file1 coumun B batches with File2 ColumnA then I want to replace corresponding File2's ColumB with File1 Column C
eg:
if File 1, B3 matches with File2 A5 then I want to replace string in B5 of file 2 with C3 of file1
Assume that File1 location is "C:\test\File1.xlsx"
so you can import File1:column A values to File2:column K by formula
File2:K1 formule
='C:\test\[File1.xlsx]Sheet1'!A1
File2:K2 formule
='C:\test\[File1.xlsx]Sheet1'!A2
and so on
Now it is easy to write formulas in File2 depends on imported values
Column Comparison Worksheet Update
Carefully adjust the constants including the Workbooks.
Copy the code into a standard module (e.g. Module1).
The Code
Option Explicit
Sub updateWorksheet()
' Source
Const srcWb As String = "Source.xlsm"
Const srcWs As String = "Sheet1"
Const srcFirstRow As Long = 2
Const srcCriteria As Variant = "B"
Const srcValue As Variant = "C"
' Target
Const tgtWb As String = "Target.xlsm"
Const tgtWs As String = "Sheet2"
Const tgtFirstRow As Long = 2
Const tgtCriteria As Variant = "A"
Const tgtValue As Variant = "B"
' Workbooks
Dim wbSrc As Workbook: Set wbSrc = Workbooks(srcWb)
'Dim wbSrc As Workbook: Set wbSrc = ThisWorkbook
Dim wbTgt As Workbook: Set wbTgt = Workbooks(tgtWb)
'Dim wbTgt As Workbook: Set wbTgt = ThisWorkbook
' Write values from Source Range to Source Array.
Dim src As Worksheet: Set src = wbSrc.Worksheets(srcWs)
Dim rng As Range
Set rng = src.Columns(srcCriteria).Find("*", , xlValues, , , xlPrevious)
If rng Is Nothing Then Exit Sub
If rng.Row < srcFirstRow Then Exit Sub
Set rng = src.Range(src.Cells(srcFirstRow, srcCriteria), rng)
Dim Source(1) As Variant: Source(0) = rng.Value
Source(1) = rng.Offset(, src.Columns(srcValue).Column - rng.Column).Value
' Write values from Target Range to Target Array.
Dim tgt As Worksheet: Set tgt = wbTgt.Worksheets(tgtWs)
Set rng = tgt.Columns(tgtCriteria).Find("*", , xlValues, , , xlPrevious)
If rng Is Nothing Then Exit Sub
If rng.Row < tgtFirstRow Then Exit Sub
Set rng = tgt.Range(tgt.Cells(tgtFirstRow, tgtCriteria), rng)
Dim Target(1) As Variant: Target(0) = rng.Value
Set rng = rng.Offset(, tgt.Columns(tgtValue).Column - rng.Column)
Target(1) = rng.Value
Dim Curr As Variant
' Write from Source Array to Target Array.
Dim i As Long
For i = 1 To UBound(Target(0))
Curr = Application.Match(Target(0)(i, 1), Source(0), 0)
If Not IsError(Curr) Then
Target(1)(i, 1) = Source(1)(Curr, 1)
End If
Next i
' Write from Target Array to Target Range.
rng.Value = Target(1)
' Inform user.
MsgBox "Data transferred.", vbInformation, "Success"
End Sub

Need help comparing values of two columns in different WorkBooks

I'm trying to compare two columns in two different WB let's say A and B which have only column each.
I'd like to msgbox a text whenever the value of cell in the column of A is also in the column of B.
I managed to put values in a variant variable and like now to compare them. I still get a 424 error at the final if statement that checks the correspondance.
Here is the code :
Option Explicit
Sub uniformisation()
Dim range1 As Variant
Dim range2 As Variant
Dim Tab1 As Variant, tab2 As Variant
Dim fichierM As Workbook
Dim fichierF As Workbook
Set fichierF = Workbooks.Open("thepath")
Set fichierMission = Workbooks.Open("thepath")
fichierF.Activate
fichierM.Activate
Dim wsF As Worksheet
Dim wsM As Worksheet
Set wsF = fichierF.Worksheets("test")
Set wsM = fichierM.Worksheets("A")
Dim C As range
Dim D As range
Set C = wsFlex.Columns(1)
Set D = wsMiss.Columns(1)
Dim TotalRows1 As Long
Dim TotalRows2 As Long
With wsF
TotalRows1 = C.Rows(Rows.Count).End(xlUp).Row
Tab1 = range(Cells(2, 1), Cells(TotalRows1, 1)).Value
MsgBox UBound(Tab1)
End With
With wsM
TotalRows2 = Rows(D.Rows.Count).End(xlUp).Row
tab2 = range(Cells(2, 2=1), Cells(TotalRows2, 1))
MsgBox UBound(tab2)
End With
For Each range1 In Tab1
For Each range2 In tab2
If range1.Value = range2.Value Then
MsgBox range1
End If
Next range2
Next range1
fichierM.Close
fichierF.Close
End Sub
Any help would be really apreciated, thanks !
you definitions are all over the place and the code is too long for what it is supposed to do. Also, you have chosen variant which is not really needed for what you want to do. Here is a shorter version that can get you started:
Sub CompareTwoColumns()
Dim rng1 As Range
Dim rng2 As Range
Dim WB1 As Workbook
Dim WB2 As Workbook
'make sure both workbooks are open
Set WB1 = Workbooks.Open("thepath1")
Set WB2 = Workbooks.Open("thepath2")
'loop through both columns and compare
For Each rng1 In WB1.Worksheets("Sheet1").UsedRange.Columns(1).Cells
For Each rng2 In WB2.Worksheets("Sheet1").UsedRange.Columns(1).Cells
If rng1.Value = rng2.Value Then
MsgBox rng1.Value
End If
Next rng2
Next rng1
End Sub

VBA - Find the next empty row in a worksheet

How can i find the next empty row in a workbook where i want to paste some content i copied early in another workbook.
This is what i get now:
Sub Retânguloarredondado1_Click()
Dim InputFile As Workbook
Dim OutputFile As Workbook
Dim Inputpath As String
Dim Outputpath As String '
Dim TP As Worksheet
Dim copyRange As Range
Dim pasteRange As Range
Dim cel As Range
Dim test As Range
Dim MyAr() As Variant
Dim n As Long
Dim LastRow As Long
' Set path for Input & Output
fileInputpath = "C:\Users\Nuno Bonaparte\Desktop\"
Outputpath = "C:\Users\Nuno Bonaparte\Desktop\"
'## Open both workbooks first:
Set InputFile = ActiveWorkbook
Set OutputFile = Workbooks.Open(Outputpath & "file2.xlsm")
Set TP = OutputFile.Worksheets("Folha1")
Set copyRange = InputFile.Sheets("file2").Range("A1,B3,C5,D7,E9")
Set pasteRange = OutputFile.Sheets("Folha1").Range("A1")
'~~> Get the count of cells in that range
n = copyRange.Cells.Count
'~~> Resize the array to hold the data
ReDim MyAr(1 To n)
n = 1
'~~> Store the values from that range into
'~~> the array
For Each cel In copyRange.Cells
MyAr(n) = cel.Value
n = n + 1
Next cel
'Now, paste to OutputFile worksheet:
OutputFile.Sheets("Folha1").Activate
pasteRange.Cells(1, 1).Resize(1, UBound(MyAr)).Value = _
MyAr
'Close InputFile & OutputFile:
'InputFile.Close
OutputFile.Save
OutputFile.Close
End Sub
The code works fine, but i would like to find the next empty row and paste the new content
Thank You.
Try this:
With OutputFile.Sheets("Folha1").Range("A:A").Find(vbNullString, [A1])
.Resize(1, Ubound(MyAr)) = MyAr
End With
Above code looks for the first empty cell after A1 and apply resize and assign value in that cell.
Is this what you're trying? You can also check this out to give you more idea. HTH.

Resources