Copy range of values between workbooks - excel

I am trying to copy either single cells values or rows of cells from a source workbook to a target workbook.
The user will have three workbooks open:
Dashboard workbook
Source workbook
Target workbook
The sub reads the user input in Dashboard workbook, which will look like the following:
Source cells Target cells Cell/Row
G28 H30 Cell
G29 H31 Row
The sub is then supposed to look up cell G28 in Source workbook and copy that into H30 in Target workbook. Likewise the sub is supposed to look up cell G29 in Source workbook and copy that cell and everything to the right into H31 in Target workbook.
I managed to copy single cell values. I have not been able to implement the functionality for the row type input.
I indicated below where the error is.
Sub transferSub()
Dim wbMain As Workbook: Set wbMain = ThisWorkbook
Dim wbMainDashboard As Worksheet: Set wbMainDashboard = wbMain.Worksheets("Dashboard")
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
'Definition of file path for source and target workbooks
sourceModel = wbMainDashboard.Range("FILE_SOURCE") 'Pull from dashboard input
targetModel = wbMainDashboard.Range("FILE_TARGET") 'Pull from dashboard input
'Source and target workbooks
Dim wbSource As Workbook: Set wbSource = Workbooks(sourceModel) 'Workbook already open
Dim wbTarget As Workbook: Set wbTarget = Workbooks(targetModel) 'Workbook already open
'Source and target worksheet
Dim wskpInput_source As Worksheet: Set wskpInput_source = wbSource.Worksheets("INPUT (kp)")
Dim wsSCEInput_source As Worksheet: Set wsSCEInput_source = wbSource.Worksheets("INPUT (SCE)")
'Source and target worksheet
Dim wskpInput_target As Worksheet: Set wskpInput_target = wbTarget.Worksheets("INPUT (kp)")
Dim wsSCEInput_target As Worksheet: Set wsSCEInput_target = wbTarget.Worksheets("INPUT (SCE)")
'Procedures
Dim rng As Range: Set rng = wbMainDashboard.Range("Dashboard!E9:E15")
Dim i As Integer
For i = 1 To rng.Rows.Count
cell_source = rng.Cells(i, 1)
cell_target = rng.Cells(i, 1).Offset(0, 1)
cell_cellrow = rng.Cells(i, 1).Offset(0, 3)
If cell_cellrow = "Cell" Then 'If cell then copy paste value in that cell
wskpInput_target.Range(cell_target) = wskpInput_source.Range(cell_source).Value
ElseIf cell_cellrow = "Row" Then 'If row then copy and paste the row of cells
wskpInput_source.Range(cell_source, cell_source.End(xlToRight)).Copy _
wskpInput_target.Range(cell_target) '---NEED HELP WITH THIS PART---
End If
Next
End Sub

Well, the Range object can either get Cells as arguments or a String (details here).
Hard-coding the range with a string argument would look like this:
wskpInput_source.Range("G28:L28").Copy _
destination:=wskpInput_target.Range(cell_target)
but since you already have a variable containing the first cell ("G28") in the row, we only need to find the last cell, you can get it with a Function like the following:
Function GetLastCellInRow(sheetName As String, firstCell As String) As String
Sheets(sheetName).Range(firstCell).End(xlToRight).Select
GetLastCellInRow = ActiveCell.Address
End Function
and this is how you call it
'MySheet is the source sheet, so you need to modify that
cell_source_last = GetLastCellInRow(MySheet.Name, cell_source)
And putting all together:
cell_source = rng.Cells(i, 1)
cell_target = rng.Cells(i, 1).Offset(0, 1)
cell_cellrow = rng.Cells(i, 1).Offset(0, 3)
'MySheet is the source sheet, so you need to modify that
cell_source_last = GetLastCellInRow(MySheet.Name, cell_source)
If cell_cellrow = "Cell" Then 'If cell then copy paste value in that cell
wskpInput_target.Range(cell_target) = wskpInput_source.Range(cell_source).Value
ElseIf cell_cellrow = "Row" Then 'If row then copy and paste the row of cells
wskpInput_source.Range(cell_source & ":" & cell_source_last).Copy _
Destination:=wskpInput_target.Range(cell_target)
End If

Related

VBA EXCEL vlookups through all sheets vs index

I have an excel file with over 200 sheets + index sheet, and I am trying to go through all sheets to copy data from index sheet. For example, I have the below table:
A test1
B test2
C test3
D test4
So I would like to do a vlookup in the index sheet, and copy the column K into the right sheet. For example, I would like "test1" to be copied in sheet "A", in cell A3. The table to vlookup is in sheet "INDEX", range J1:K4.
Is that possible? I stored a file here! For confidentiality reason, I've edited sheet names and content, and put a shorter file.
Thanks in advance!
Update Worksheets
Option Explicit
Sub updateWorksheets()
' Define constants.
Const wsName As String = "INDEX"
Const FirstCellAddress As String = "J1"
Const dstAddress As String = "A3"
Dim wb As Workbook: Set wb = ThisWorkbook ' Workbook containing this code.
' Define Data Range.
Dim rng As Range
With wb.Worksheets(wsName).Range(FirstCellAddress).Resize(, 2)
Set rng = .Resize(.Worksheet.Rows.Count - .Row + 1).Find( _
What:="*", _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious)
If rng Is Nothing Then
Exit Sub
End If
Set rng = .Resize(rng.Row - .Row + 1)
End With
' Write values from Data Range to Data Array.
Dim Data As Variant: Data = rng.Value
' Declare additional variables (to be used in the 'For Next' loop).
Dim dst As Worksheet ' Current Destination Worksheet
Dim i As Long ' Data Array Row Counter
' Loop through rows of Data Array.
For i = 1 To UBound(Data, 1)
' Use the value in the first column to try to create a reference
' to the worksheet i.e. check if the worksheet exists.
Set dst = Nothing
On Error Resume Next
Set dst = wb.Worksheets(Data(i, 1))
On Error GoTo 0
' If the worksheet exists,...
If Not dst Is Nothing Then
' ...write value from second column of Data Array
' to Destination Cell Range in Current Destination worksheet.
dst.Range(dstAddress).Value = Data(i, 2)
End If
Next i
End Sub

Selectively copy and paste rows with given criteria

I am trying to select rows in a table based on the word "Yes" being present in column J.
I have a table going from column A to J, and I want to select the rows where there is a "Yes" in column J and paste only those rows into a new sheet.
Once selected, I need to copy these rows to a new sheet or word document.
I have tried a range of forumulas, this is for Windows MS Excel software, using a VBA Macro.
I am using the following VBA, but having issues:
Sub Macro1()
Dim rngJ As Range
Dim cell As Range
Set rngJ = Range("J1", Range("J65536").End(xlUp))
Set wsNew = ThisWorkbook.Worksheets.Add
For Each cell In rngJ
If cell.Value = "Yes" Then
cell.EntireRow.Copy
wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
End If
Next cell
End Sub
Any help would be very much appreciated!
Rather than finding, copying and pasting for each cell, why not find all, then copy and paste once like this:
Sub Macro1()
Dim rngJ As Range
Dim MySel As Range
Set rngJ = Range("J1", Range("J" & Rows.Count).End(xlUp))
Set wsNew = ThisWorkbook.Worksheets.Add
For Each cell In rngJ
If cell.Value = "Yes" Then
If MySel Is Nothing Then
Set MySel = cell.EntireRow
Else
Set MySel = Union(MySel, cell.EntireRow)
End If
End If
Next cell
If Not MySel Is Nothing Then MySel.Copy Destination:= wsNew.Range("A1")
End Sub
It's better to avoid using Select as much as possible; see this link.
Use something like this
Option Explicit
Public Sub CopyYesRowsToNewWorksheet()
Dim wsSource As Worksheet
Set wsSource = ThisWorkbook.ActiveSheet 'better define sheet by name ThisWorkbook.Worksheets("SourceSheet")
Dim DataRangeJ As Variant 'read "yes" data into array for faster access
DataRangeJ = wsSource.Range("J1", wsSource.Range("J" & wsSource.Rows.Count).End(xlUp)).Value
Dim wsNew As Worksheet
Set wsNew = ThisWorkbook.Worksheets.Add
Dim NextFreeRow As Long
NextFreeRow = 1 'start pasting in this row in the new sheet
If IsArray(DataRangeJ) Then
Dim iRow As Long
For iRow = LBound(DataRangeJ) To UBound(DataRangeJ) 'loop through data array
If DataRangeJ(iRow, 1) = "yes" Then
wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value 'copy the values of the row
NextFreeRow = NextFreeRow + 1
End If
Next iRow
ElseIf DataRangeJ = "yes" Then 'if only the first row has data
wsNew.Rows(NextFreeRow).Value = wsSource.Rows(1).Value
End If
End Sub
The line
wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value
only copys the value without formatting. If you also want to copy the formatting replace it with
wsSource.Rows(iRow).Copy Destination:=wsNew.Rows(NextFreeRow)

Why does my code not work when using ist over workbook-boundaries but work when using it in the same Workbook?

I have a workbook with two worksheets.
The first sheet contains a list of email adresses.
The second sheet contains a list of email adresses of which some match the ones in first sheet and some may not
I added a button and some code (see below). When i hit the button excel looks in sheet2 and compares it with the email addresses in sheet1 ... if it finds equal email-addresses it adds the found email address & the "allowed"-state behind the existing address in sheet1.
This is working fine:
Private Sub CommandButton1_Click()
Call lookup
End Sub
Sub lookup()
Dim TotalRows As Long
Dim rng As Range
Dim i As Long
'Copy lookup values from sheet1 to sheet3
Sheets("Tabelle1").Select
TotalRows = ActiveSheet.UsedRange.Rows.Count
For i = 1 To TotalRows
'Search for the value on sheet2
Set rng = Sheets("Tabelle2").UsedRange.Find(Cells(i, 1).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
Cells(i, 2).Value = rng.Value
Cells(i, 3).Value = "Allowed"
End If
Next
End Sub
But now I want to have the button in one "trigger.xlsm"-file and the data is in two different workbooks. ...so i have one button to copy the compare data from workbook2 to sheet2 in workbook1.... this works well!
But the rest of the code that compares and writes the equal mail-addresses in workbook1 - sheet1 does not... every line is filled with "allowed"-state.
I tried with this code which gives the above result:
Private Sub CommandButton1_Click()
Workbooks.Open "C:\Users\DEJP0050\Documents\testvon.xlsx"
Workbooks.Open "C:\Users\DEJP0050\Documents\testnach.xlsm"
Workbooks("testvon.xlsx").Sheets("Tabelle1").Range("A:A").Copy _
Workbooks("testnach.xlsm").Sheets("Tabelle2").Range("A:A")
Workbooks("testvon.xlsx").Close SaveChanges:=True
Workbooks("testnach.xlsm").Close SaveChanges:=True
End Sub
Private Sub CommandButton2_Click()
Call lookup
End Sub
Sub lookup()
Dim TotalRows As Long
Dim rng As Range
Dim i As Long
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Users\DEJP0050\Documents\testnach.xlsx")
Dim ws11 As Worksheet
Set ws11 = wb1.Sheets("Tabelle1")
Dim ws12 As Worksheet
Set ws12 = wb1.Sheets("Tabelle2")
'Copy lookup values from sheet1 to sheet3
'ws11.Select
TotalRows = ws11.UsedRange.Rows.Count
'Range("A1:A" & TotalRows).Copy
Destination:=Sheets("Tabelle3").Range("A1")
'Go to the destination sheet
'Sheets("Tabelle3").Select
For i = 1 To TotalRows
'Search for the value on sheet2
Set rng = ws12.UsedRange.Find(Cells(i, 1).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
ws11.Cells(i, 2).Value = rng.Value
'Cells(i, 2).Value = "Allowed"
ws11.Cells(i, 3).Value = "Allowed"
End If
Next
Workbooks("testnach.xlsx").Close SaveChanges:=True
End Sub
Why does it work when the button is within the same workbook, but doesnt work when the button is in another workbook?
Maybe you need to change
Sheets("Tabelle1").Select
to
activeworkbook.Sheets("Tabelle1").Select
AND
TotalRows = ActiveSheet.UsedRange.Rows.Count
to
TotalRows = activeworkbook.ActiveSheet.UsedRange.Rows.Count
AND
Set rng = Sheets("Tabelle2").UsedRange.Find(Cells(i, 1).Value)
to
Set rng = activeworkbook.Sheets("Tabelle2").UsedRange.Find(activeworkbook.Sheets("Tabelle2").Cells(i, 1).Value)

Copy/Paste Yellow Highlighted Cells in a new WorkSheet VBA

I'm trying to get this one done.
This macro should open a workbook (workbook names always change and there's always just one sheet to process). This works.
Set the range for the whole sheet; works fine.
And search the entire sheet for cells highlighted in yellow, and copy these cells into a new sheet... and this is where I need help!
I am really new to VBA and thats what I have so far:
Option Explicit
Sub test3()
Dim data As Variant
Dim rngTemp As Range
Dim cell As Range
'//open Workbook
data = Application.GetOpenFilename(, , "Open Workbook")
Workbooks.Open data
'// set Range ( Whole Sheet)
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
Range(Cells(1, 1), rngTemp).Select
End If
'// Search for Yellow highlighted Cells and (if you find one)
'// Copy Cell B1 + the 3rd Cell in the column (of the highlighted Cell) + the value highlighted Cell
'// and paste in new Sheet
For Each cell In rngTemp.Cells
If rngTemp.Interior.ColorIndex = 6 Then
cell.Select
Selection.Copy
Sheets.Add
Range("A1").PasteSpecial
Application.CutCopyMode = False
End If
Next
End Sub
Sub test3()
Dim wbName As string
Dim rngTemp As Range
Dim r As Range
DIM TARGETSHEET AS WORKSHEET
DIM TARGET AS RANGE
'//open Workbook
wbName = Application.GetOpenFilename(, , "Open Workbook")
if wbName = "" or wbname = "CANCEL" then exit sub
Workbooks.Open wbname
'// set Range ( Whole Sheet)
Set rngTemp = Activesheet.usedrange
SET TARGETSHEET = ACTIVEWORKBOOK.WORKSHEETS.ADD()
SET TARGET = TARGETSHEET.RANGE("A1")
'// Search for Yellow highlighted Cells and (if you find one)
'// Copy Cell B1 + the 3rd Cell in the Column (of the highlighted Cell) + the value highlighted Cell
'// and paste in new Sheet
For Each r In rngTemp
If r.Interior.ColorIndex = 6 Then
TARGET = rngtemp.parent.range("B1")
TARGET.OFFSET(0,1) = r
TARGET.OFFSTE(0,2) = rngtemp.parent.cells(3,r.column)
'I've assumed you want them across the first row
SET TARGET = TARGET.OFFSET(1,0)
End If
Next r
End Sub

Create copies of original workbook inputting new data from list

Trying to copy my original worksheet but with different data for as many items in a list/array.
My original worksheet is formatted in such a way it references the cells in the data array worksheet.
For example
TEST TIME Output1 Output2
A 3 5 9
. . . .
. . . .
. . . .
Z 2 9 4
Above would be something like my data array worksheet and I would reference the cells to the formatted worksheet. The end result would be 26 worksheets named A test, B test, ..., and Z test.
Is there a way to copy a worksheet over and over creating new reference cells going down an array?
What I have:
Sub AddSheets()
Dim cell As Excel.Range
Dim SCHPipe As Excel.Worksheet
Dim MacroTBF1 As Excel.Workbook
Set SCHPipe = ActiveSheet
Set MacroTBF1 = ActiveWorkbook
For Each cell In SCHPipe.Range("B12:B15")
With MacroTBF1
.Sheets("OriginalTBF").Copy after:=.Sheets(.Sheets.Count)
End If
Next cell
End Sub
I do not know how to reference the data to each sheet being created. This keeps getting an invalid error message.
Something like this, you will need to adjust for the layout of your data and template sheet:
Sub AddSheets()
Dim cell As Range
Dim SCHPipe As Worksheet, shtOrig As Worksheet
Dim MacroTBF1 As Workbook, shtNew As Worksheet
Set SCHPipe = ActiveSheet
Set MacroTBF1 = ActiveWorkbook
Set shtOrig = MacroTBF1.Sheets("OriginalTBF")
For Each cell In SCHPipe.Range("B12:B15")
If cell.Value <> "" Then
shtOrig.Copy after:=MacroTBF1.Sheets(MacroTBF1.Sheets.Count)
Set shtNew = MacroTBF1.Sheets(MacroTBF1.Sheets.Count)
With shtNew
.Name = cell.Value & " Test"
.Range("A1").Value = cell.Value
.Range("A2").Value = cell.Offset(0, 1).Value
.Range("D49").Value = IIf(cell.Offset(0, 1).Value = "-", _
cell.Offset(0, 5).Value, "")
End With
End If
Next cell
End Sub

Resources