Copying a specific range into another excel workbook - excel

I am looking to export a specific range of data from one workbook to a master workbook. I have already figured out how to overall copy from one to another but I'd like to modify my existing coding. Currently, the macro is taking all of row 2 from the workbook and copying it into this master file which is working great, however I am looking to do some more things in the master file so I need just columns A2:HD2 to copy and paste into the master sheet. Below is what we are using, can anyone help me figure out how to just get A2:HD2 and not all of row 2 into my master sheet?
Dim LN, Match As Integer
Dim wb As Workbook
Dim Name As String
Name = "Master sheet path here"
Application.ScreenUpdating = False
Sheets("LADB Bulk Upload").Select
LN = Range("A2").Value
Rows("2:2").Select
Selection.Copy
Set wb = Workbooks.Open(Filename:=Name)
If IsError(Application.Match(LN, ActiveSheet.Range("A:A"), 0)) Then
Range("A100000").End(xlUp).Select
ActiveCell.Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Else
Match = Application.Match(LN, wb.Sheets("Sheet1").Range("A:A"), 0)
Cells(Match, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.ScreenUpdating = True

Replace
Rows("2:2").Select
Selection.Copy
With
Range("A2:HD2").Copy
Ideally you should work with ranges instead of using Select. You'll find plenty of information about that elsewhere. That said, if the code works, and isn't especially slow, it hardly matters.

This code is refactored to copy only the A2:HD2 range, and without using Select
Option Explicit
Public Sub CopyA2HD2()
Dim mainWb As Workbook, mainWs As Worksheet, mainLr As Long, mainCol As Range
Dim thisWs As Worksheet, findTxt As String, foundCell As Variant
Set thisWs = ThisWorkbook.Worksheets("LADB Bulk Upload") 'Current file
Application.ScreenUpdating = False
On Error Resume Next 'Expected errors: File not found, and Sheet Name not found
Set mainWb = Workbooks.Open(Filename:="Master sheet path here")
If Err.Number = 0 Then 'If master file is found, and open, continue
Set mainWs = mainWb.Worksheets("Sheet1")
If Err.Number > 0 Then Exit Sub 'If "Sheet1" in master file is not found exit
mainLr = mainWs.Cells(mainWs.Rows.Count, "A").End(xlUp).Row 'Last row in master
Set mainCol = mainWs.Range(mainWs.Cells(1, "A"), mainWs.Cells(mainLr, "A"))
findTxt = thisWs.Range("A2").Value
foundCell = Application.Match(findTxt, mainCol, 0) 'Search column A in master
If Not IsError(foundCell) Then 'If text was found in master
Set foundCell = mainWs.Cells(foundCell, "A") 'Copy A2:HD2 to same row
Else
Set foundCell = mainWs.Cells(mainLr + 1, "A") 'Else, copy A2:HD2 to last row
End If
thisWs.Range("A2:HD2").Copy
foundCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
foundCell.Select
Application.CutCopyMode = False
mainWb.Close SaveChanges:=True
End If
Application.ScreenUpdating = True
End Sub
A few notes about your code
As already mentioned, avoid using Select and Activate if possible
Use Option Explicit at the top of every module, so the compiler can catch missing variables
Don't use reserved keywords as variable names to avoid shadowing the built-in objects
Words like Name, Match, etc
Use Long variable type instead of Integer
According to MSDN VBA silently converts all Integers to Longs
Always refer to ranges explicitly: Rows("2:2") implicitly uses the ActiveSheet
It takes a lot of care and maintenance work to make sure that the expected sheet is active
Code indentation and proper vertical white-space will help visualize structure and flow clearer

Related

VBA Copy and pastevalues in another sheet using offset

I want to create an excel with a macro which does this:
It takes a values from one sheet and paste them in another sheet in the first empty Row. I currently have this and this does paste but then the formula, not the values. When I change Paste to Pastespecial it does not work anymore. Can anybody help me with this?
Sub CopyPasteSpecial()
Set wsA = Sheet3
Set wsW = Sheet5
wsA.Range("A3").Copy
Sheet5.Activate
Dim i As Integer
Application.ScreenUpdating = False
NumRows = Range("C5", Range("C5").End(xlDown)).Rows.Count
Range("C5").Select
For i = 1 To NumRows
ActiveCell.Offset(1, 0).Select
Next
Application.ScreenUpdating = True
ActiveSheet.Paste
The (accepted) answer of Sachin Kohli contains so many problems that it is too much to write in a comment. All of them causes errors that can be found thousend times on Stackoverflow.
(a) DonĀ“t use Select and Activate - https://stackoverflow.com/a/10718179/7599798 - You have already a worksheet variable to sheet5 (wsW), so use it.
(b) Copying data (values) between ranges (=cells) can be done without Copy&Paste. This is much faster.
(c) When dealing with row and column numbers, use datatype Long, else you risk an overflow error in large sheets. Basically, use always Long instead of Integer - the data type Integer exists only for historic reasons.
(d) Always put Optiona Explicit at the top of your code and declare all variables. This will save you a lot of headaches because typos in variable names will be caught by the compiler.
Sub CopyPasteSpecial()
Dim wsA As Worksheet, wsW As Worksheet
Set wsW = ThisWorkbook.Sheets("Sheet2")
Set wsA = Sheet1
Set wsW = Sheet2
Dim lastRow As Long
lastRow = wsW.Cells(wsW.Rows.Count, "C").End(xlUp).Row
wsW.Cells(lastRow + 1, "C").Value = wsA.Range("A3").Value
End Sub
Try this below code for pasting as values & no need to iterate to get to the last empty row as well...
Sub CopyPasteSpecial()
Set wsA = Sheet3
Set wsW = Sheet5
wsA.Range("A3").Copy
Sheet5.Activate
Dim i As Integer
Application.ScreenUpdating = False
NumRows = Range("C5", Range("C5").End(xlDown)).Rows.Count
Range("C" & NumRows + 5).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Hope this Helps...

Excel Macro & VBA, Copy Cell Range to another sheet (transposed and based on another value)

I have tried to frankenstein a solution from different threads but I am very much a newbie to VBA and programming, so it has not been going too well...
Here's some basic info:
I have 2 Sheets within the same workbook (Database and Data entry)
They contain the same headers, but are transposed (Database has the headers in the columns while Data entry has them in the rows)
Now, I am looking for 3 things (ideally in one compact solution)
Have a Command Button that copies and transposes the most recent range (leftmost column) from Data Entry to Database. (This is done in the code below)
This should be done depending on a certain cell value on the data entry sheet (ideally that cell could stay part of the copied range, however this is not crucial)
Delete the original range from the data entry sheet.
As I said I'm just starting to work with VBA so I am completely unsure how to go about this, I have attached what I gathered so far (excludes Nr.2 and feels very cumbersome overall). Any help is very much appreciated!
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim xSheet As Worksheet
Set xSheet = ActiveSheet
If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
xSheet.Range("E6:E200").Copy
Worksheets("Sheet1").Range("E6:AZ6").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End If
Application.ScreenUpdating = True
End Sub
Check this one. It checks the value of E10. If it's "Y", then data is copied and deleted from original place. Otherwise, it shows a message to the user.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim xSheet As Worksheet
Set xSheet = ActiveSheet
If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
If xSheet.Range("E10")="Y"
xSheet.Range("E6:E200").Copy
Worksheets("Sheet1").Range("E6:AZ6").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
xSheet.Columns("E").Delete
Else
MsgBox("Data entry not ready!")
End If
End If
Application.ScreenUpdating = True
End Sub

VBA - merging data from different workbooks keeping formats

I have tried to simplify the whole coding actually as nothing seemed to work. To recap:I have a folder with 51 Excel files. In each file there are specific variables between cell J4 and cell R4, included, that I want to tranfer into an inclusive excel workbook keeping the original format. The code that I am using is the following:
*** I have defined my variables ***
Sub LoopThroughDirectory()
Dim MyFile As String
Dim pp As Workbook
Dim row As Integer
row = 1
***this is the folder that has my 51 excel files***
MyFile = Dir("C:\Users\Aaa\Desktop\Analysed Data\*.xls*")
***consider all the files until the end, sheet 1, range, copy, close***
Do While MyFile <> ""
Workbook.Open ("C:\Users\Aaa\Desktop\Analysed Data\")
Worksheets("sheet1").Select
Range("J4:R4").Select
Selection.Copy
ActiveWindow.Close
***go to my workbook, sheet 1, row 1. Select A1 and paste special values and format***
Set pp = Workbook
Windows("pp.xlsx").Activate
Worksheets("sheet1").Cells(row, 1) = MyFile
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
***do it in loop for all my excel files, and copy-pastespecial the range of values each time in the following row***
row = row + 1
Loop
End Sub
it doesn't work like that either but I thought that if I get rid of the erow probably the process would be more straightforward and that if I explain what I mean with my coding, it's easier to get help. Thank you for your help. Silvia

how to paste only values in excel

I'm quite new to Excel and completely new to this forum.
I have taken the code from the below forum and modified it to my need.
http://pressf1.pcworld.co.nz/showthread.php?90122-Creating-Macro-to-copy-and-paste-data-into-the-next-empty-column.
Sub copyTotals()
Dim TargetSht As Worksheet, SourceSht As Worksheet, SourceRow As Integer, SourceCells As Range
Set SourceSht = ThisWorkbook.Sheets("DUN - Jan")
Set TargetSht = ThisWorkbook.Sheets("DUN Jan - Jan,Feb,Mar,Apr")
Set SourceCells = SourceSht.Range("L36,N36")
If TargetSht.Range("C11").Value = "" Then
SourceRow = 1
ElseIf TargetSht.Range("C41") <> "" Then
MsgBox ("The sheet is full, you need to create a new sheet")
Else
SourceRow = TargetSht.Range("C41").End(xlUp).Row + 1
End If
SourceCells.Copy TargetSht.Cells(SourceRow, 3)
End Sub
The problem is that the values pasted have the formating of the source and i only want to paste the values.
Can someone please help me with this.
Use .Copy together with .PasteSpecial. Instead of:
SourceCells.Copy TargetSht.Cells(2, SourceCol)
Do this:
SourceCells.Copy
TargetSht.Cells(2, SourceCol).PasteSpecial xlPasteValues
Using the macro recorder yields this kind of thing. I use it a lot when stuck.
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
You don't need to copy and paste to do this (at least in Excel 2010 and above, I think). You just set the .Value of the range to equal itself. eg:
rng.Value = rng.Value
or
Sheet1.Range("A1:A10").Value = Sheet1.Range("A1:A10").Value
since .Value "Returns or sets a Variant value that represents the value of the specified range."
Note that this just works for values, not formats.
http://msdn.microsoft.com/en-us/library/office/ff195193(v=office.15).aspx
right click in the cell and select paste special then you can choose values only
edit: for macros its the same principle
use
.PasteSpecial xlPasteValues
like here
Set rng6 = .Range("A3").End(xlDown).Offset(0, 41)
rng6.Copy
ActiveSheet.Paste Destination:=Worksheets("Positions").Range("W2")

Search for sheets' name if matched condition then copy paste value with format?

Update: I was able to solve this problem. I just remembered VBA use * and ? to present the string 'If Sheet.name Like "*CopyA"'
I would like to make a copy special value with original format of the sources of all sheets contains the word: "CopyA" for example "Apple CopyA","Mango CopyA"
I can use the macro record to see how VBA create sheet and copy special like similar example below.
I am having trouble in the searching for sheet name - All examples I found either I must know exact name (same as Macro record) or I have to make a copy of all sheets (loop though all sheet and copy, no matter the name is).
Sub Macro1()
Sheets("Sheet1").Select
Sheets("Sheet1").Copy Before:=Sheets(1)
Sheets("Sheet1(2)").Select
Cells.Select
Selection.Copy
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
How can I search for sheet's name? In this case, any sheet that has "CopyA"?
Another way :) You can also use Instr(). For example
For all sheets in the workbook, use this
Option Explicit
Sub Macro1()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
If InStr(1, ws.Name, "CopyA") Then
'~~ > Your code
End If
Next
End Sub
For ActiveSheet use this
Option Explicit
Sub Macro1()
If InStr(1, ActiveSheet.Name, "CopyA") Then
'~~ > Your code
End If
End Sub

Resources