Paste Special Transpose for multiple files - vba

First, I begin with having a Master File. The Master File has names of 40 other workbooks.
I need to write a VBA code that works on this 40 workbooks (names defined in A1-A40 in the masterfile). This code should go to each workbook, open it, and copy the data in the first sheet of each workbook.
Thereafter, it will go back to the Master workbook and paste special in separate new sheets. For example, workbookA1's data goes into Sheet1 and workbookA2's data goes into Sheet2. However, I am having some trouble with it. The error says "PasteSpecial Method of Range Class" failed.
Sub Macro2()
Dim thiswb As Workbook, datawb As Workbook
Dim datafolder As String
Dim cell As Range, datawblist As Range
Dim i As Integer
Set thiswb = ActiveWorkbook
i = 2
'Have the 40 file names in sheet2 of this workbook in cells A1:A40
Set datawblist = Sheets("command").Range("A1:A4")
datafolder = "C:\Users\bryan\Desktop\Y4S1\Money and Banking\Empirical\QuarterSheets\2012q1\" 'change this to your directory they're in
For Each cell In datawblist
Workbooks.Open Filename:=datafolder & cell & ".csv", ReadOnly:=True
Set datawb = ActiveWorkbook
Sheets(1).Select 'change this to the sheet name you need to copy from
Range("A1:XFD1048576").Select
Do Until ActiveCell.Value = ""
Selection.Copy
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
thiswb.Activate
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=True
ActiveCell.Offset(0, 4).Select
datawb.Activate
ActiveCell.Offset(0, 1).Select
Loop
datawb.Close savechanges:=False
thiswb.Activate
Sheets("command").Select
i = i + 1
Cells(i, 1).Select
Next
End Sub

Try this, which removes the Selects and Activates, and restricts the copied range to the used range rather than every single cell. I think I've interpreted your scenario correctly, but shout if not.
Sub Macro2()
Dim thiswb As Workbook, datawb As Workbook, ws As Worksheet
Dim datafolder As String
Dim cell As Range, datawblist As Range
Dim i As Long
Set thiswb = ThisWorkbook
i = 2
'Have the 40 file names in sheet2 of this workbook in cells A1:A40
Set datawblist = thiswb.Sheets("command").Range("A1:A4")
datafolder = "C:\Users\bryan\Desktop\Y4S1\Money and Banking\Empirical\QuarterSheets\2012q1\" 'change this to your directory they're in
For Each cell In datawblist
Set datawb = Workbooks.Open(Filename:=datafolder & cell & ".csv", ReadOnly:=True)
Set ws = thiswb.Sheets.Add(After:=thiswb.Worksheets(Worksheets.Count))
datawb.Sheets(1).UsedRange.Copy
ws.Range("A1").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=True
datawb.Close savechanges:=False
Next
End Sub

Related

Excel VBA: Subscript out of range code fix

I keep getting a subscript out of range error in the line
Sheets("Dump").Select
How can I adjust my code to remove the error? And is there a way to adjust this to remove the .Select
Sub UploadData()
'open the source workbook and select the source
Dim wb As Workbook
Workbooks.Open Filename:=Sheets("Instructions").Range("$B$4").value
Set wb = ActiveWorkbook
Sheets("Invoice Totals").Select
'copy the source range
Sheets("Invoice Totals").Range("A:R").Select
Selection.Copy
'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("A2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
' copy the source range
Sheets("Lease & RPM Charges").Range("A:AH").Select
Selection.Copy
'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("T2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
'copy the source range
Sheets("MMS_Service_And_Repairs").Range("A:R").Select
Selection.Copy
'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("BC2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
'close the source workbook
wb.Close
End Sub
Edit(Fixed issues) Try this...(Tested on mock data).
Sub UploadData()
Dim wb As Workbook
Dim lRow As Long, lRow2 As Long, lRow3 As Long 'Set lastrow for each source worksheet
Dim rng As Range, rng2 As Range, rng3 As Range 'Set range for each source worksheet
'open the source workbook using the filename in cell B4(I'm making an assumption that the
'source workbook is located in the same folder as the Thisworkbook
Set wb = Workbooks.Open(Filename:=Sheets("Instructions").Range("$B$4").Value)
With wb
With .Sheets("Invoice Totals") 'Copy the range on this ws and paste to "Dump" in dest ws
lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range("A1:R" & lRow)
rng.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("A2")
End With
With .Sheets("Lease & RPM Charges") 'Copy the range on this ws and paste to "Dump" in dest ws
lRow2 = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng2 = .Range("A1:AH" & lRow2)
rng2.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("T2")
End With
With .Sheets("Invoice Totals") 'Copy the range on this ws and paste to "Dump" in dest ws
lRow3 = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng3 = .Range("A1:R" & lRow3)
rng3.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("BC2")
End With
With ThisWorkbook.Sheets("Dump").UsedRange
.Value = .Value 'Sets all the data in the usedrange to values only
End With
End With
wb.Close 'close the source workbook
End Sub

Copy variable range of values not formulas

I'm trying to copy a variable range from one book (Book1) to the end of a variable range of the another book (book2). I'm interested only in values of the variable range in the book 1 and this is the problem. So I need to find the last row of values (not formulas). On this forum I found several options but none of them works in my case. Here is what I got (Please see the second part of the code "Copy Detail USHB"-'Select cells to copy):
''''''Copy Detail by Vendor''''''
'Last cell in column
Dim WS As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long
Set WS = Worksheets("Detail by Vendor")
With WS
Set LastCell = .Cells(.Rows.Count, "B").End(xlUp)
LastCellRowNumber = LastCell.Row + 1
End With
Dim wb As Workbook, wb2 As Workbook
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
Workbooks.Open Filename:= _
"Book2.xlsm"
'Set selectedworkbook
Set wb2 = ActiveWorkbook
'Select cells to copy
Sheets("By Vendor").Select
Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
'Go back to original workbook you want to paste into
wb.Activate
Sheets("Detail by Vendor").Select
'Paste starting at the last empty row
wb.Worksheets("Detail by Vendor").Range("B" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
'''''Copy Detail USHB'''''
'Last cell in column
Set WS = Worksheets("Detail USHB")
With WS
Set LastCell = .Cells(.Rows.Count, "B").End(xlUp)
LastCellRowNumber = LastCell.Row + 1
End With
'Activate the target workbook
wb2.Activate
'Select cells to copy
Sheets("Detail USHB").Select
Dim jLastRow As Long
jLastRow = Columns("B").Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Range(Selection, ActiveCell.SpecialCells(xlLastRow).Select
Selection.Copy
'Go back to original workbook you want to paste into
wb.Activate
Sheets("Detail USHB").Select
'Paste starting at the last empty row
wb.Worksheets("Detail USHB").Range("B" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Following your comments, I believe you are trying to do the following:
'...
'''''Copy Detail USHB'''''
Dim D As Range
Dim S As Range
With wb2.Worksheets("Detail USHB")
'Locate the last non-blank value in source range
LastRow = .Range("B:B").Find(What:="*", _
LookIn:=xlValues, _
SearchDirection:=xlPrevious).Row
'Set range
Set S = .Range("B2:B" & LastRow)
End With
With wb.Worksheets("Detail USHB")
'Find last used cell in destination range
Set D = .Range("B" & .Rows.Count).End(xlUp)
'Offset to next row, and resize appropriately
Set D = D.Offset(1, 0).Resize(LastRow - 1, 1)
End With
'Copy values
D.Value = S.Value
End Sub

Excel VBA copy from one sheet to another wb doesnt overwrite data

I use vba to import data from one wb to another - but it seems like the data is not overwriten.
ex.
wb 1 cell A2 contains the number "2" and is copied to wb 2 cell A2.
But if I delete cell A2 from wb 2, and run the vba again - there is no data entered in wb 2 cell A2...
Can anyone see why this is?
Regards
Brian
Sorry forgot to add code :o)
Sub GetData()
Dim strWhereToCopy As String, strStartCellColName As String
Dim strListSheet As String
Application.ScreenUpdating = False
strListSheet = "List"
On Error GoTo ErrH
Sheets(strListSheet).Select
Range("B2").Select
'this is the main loop, we will open the files one by one and copy their data into the masterdata sheet
Set currentWB = ActiveWorkbook
Do While ActiveCell.Value <> ""
strFileName = ActiveCell.Offset(0, 1) & ActiveCell.Value
strCopyRange = ActiveCell.Offset(0, 2) & ":" & ActiveCell.Offset(0, 3)
strWhereToCopy = ActiveCell.Offset(0, 4).Value
strStartCellColName = Mid(ActiveCell.Offset(0, 5), 2, 1)
Application.Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=True
Set dataWB = ActiveWorkbook
Range(strCopyRange).Select
Selection.Copy
currentWB.Activate
Sheets(strWhereToCopy).Select
lastRow = LastRowInOneColumn(strStartCellColName)
Cells(lastRow + 1, 1).Select
Selection.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
dataWB.Close False
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select
Loop
Sheets(strListSheet).Select
Range("B2").Select
Exit Sub
ErrH:
MsgBox "It seems some file was missing. The data copy operation is not complete."
Exit Sub
'Application.ScreenUpdating = True
End Sub
you can copy wb1 and past it as wb2
Sub Copy_One_File()
Dim wb1, wb2 As String
wb1 = ActiveWorkbook.Path & "wb1.xlsm"
wb2 = ActiveWorkbook.Path & "wb2.xlsm"
FileCopy wb1, wb2
End Sub
this is the simplest method
you should avoid Select/Selection/Activate/ActiveXXXpattern in favour of a fully qualified range reference
like in the following (commented) code:
Option Explicit
Sub GetData()
Dim strWhereToCopy As String, strStartCellColName As String
Dim strFileName As String
Dim strCopyRange As Range, cell As Range
Dim LastRow As Long
With Sheets("List") '<--| reference your "List" worksheet
For Each cell In .Range("B2", .Cells(.Rows.count, "B").End(xlUp)).SpecialCells(xlCellTypeConstants) '<--| loop through its column "B" not empty cells form row 2 down to last not empty one
With cell '<--| reference current cell
strFileName = .Offset(0, 1) & .Value
strCopyRange = .Offset(0, 2) & ":" & .Offset(0, 3)
strWhereToCopy = .Offset(0, 4).Value
strStartCellColName = Mid(.Offset(0, 5), 2, 1)
End With
On Error GoTo ErrH '<--| activate error handler for subsequent file open statement
Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=True
On Error GoTo 0 '<--| resume "default" error handling
Range(strCopyRange).Copy '<-- without a leading dot (.) the range referes to the currently active worksheet, which is the active one in the just opened workbook
With .Parent '<--| reference workbook where currently referenced Sheet "List" resides in
LastRow = LastRowInOneColumn(.Worksheets(strWhereToCopy), strStartCellColName) '<--| your 'LastRowInOneColumn' function must be passed a worksheet reference, too
With .Worksheets(strWhereToCopy).Cells(LastRow + 1, 1) '<--| reference 'strWhereToCopy' named worksheet in the referenced workbook
.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
End With
ActiveWorkbook.Close False
Next cell
.Activate
.Range("B2").Select
End With
Exit Sub
ErrH:
MsgBox "It seems some file was missing. The data copy operation is not complete."
End Sub
as per comments, your LastRowInOneColumn function must be passed a worksheet object reference too and fully qualify the column range reference to search the last row in
the function signature and its pseudocode is:
Function LastRowInOneColumn(sht As Worksheet, strStartCellColName As String) As Long
With sht
'here goes your actual 'LastRowInOneColumn' code
' only you have to put a dot (.) before each range reference
End With
End Function

Issue with For Loop to paste special a row across worksheets

I am trying to copy the last row and paste special at the next row. When I try the following code for an individual worksheet it works fine:
Sub Macro1()
Dim LR As Long
LR = Range("E" & Rows.Count).End(xlUp).Row
Rows(LR).Select
Selection.Copy
Rows(LR + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
But when I am trying to loop through all worksheets, it is only pasting special in one of the worksheets the same copied row number of times instead of repeating to each worksheet. Could you please advise what I am doing wrong on the following for loop?
Sub Macro1()
Dim ws As Worksheet
Dim wb As Workbook
Dim LR As Long
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
If ws3.Name Like "*.plt" Then
LR = Range("E" & Rows.Count).End(xlUp).Row
Rows(LR).Select
Selection.Copy
Rows(LR + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next ws
End Sub
Thanks in advance!
To save some overhead, you should first refrain from using .Select and .Selection.*. If you anyways want to copy just the value you should do so via the .Value property of the cell. Secondly, you should use the With statement to make sure that you are referencing the target sheet. Finally, you should set unused objects to Nothing in the end. The following code should do the trick.
Code
Sub Macro1()
Dim ws As Worksheet
Dim wb As Workbook
Dim rng As Range
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
With ws
If .Name Like "*.plt" Then
Set rng = .Range("E" & Rows.Count).End(xlUp).EntireRow
rng.Offset(1).Value = rng.Value
End If
End With
Next ws
Set ws = Nothing
Set rng = Nothing
Set wb = Nothing
End Sub
I think that this
If ws3.Name Like "*.plt" Then
might be your issue. You need to enable Option Explicit so that you do not use undefined names.
Also, make
Set wb = ActiveWorkbook
to
Set wb = ThisWorkbook

Excel VBA - choose workbook to copy from and paste into existing workbook on next blank row

I am new to VBA and have been using the site to piece together a solution.
I need to write a macro that prompts the user to open a file (wb2), copy a row of data from a Sheet1 in that workbook (wb2) and then paste it into the next empty row within the original workbook (wb) also on Sheet1. I got it to work up until I tried adding the code for pasting in the next empty row - I am now receiving the following error message, "Run-time error '438': Object doesn't support this property or method"
Any help would be greatly appreciated.
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set selectedworkbook
Set wb2 = ActiveWorkbook
wb2.Range("A3:E3").Select
Selection.Copy
wb.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
wb2.Close
'Set targetworkbook
Set wb = ActiveWorkbook
End Sub
Just a quick note on the subject:
Instead of
wb2.Worksheets("Output").Range("J3:R3").Select
Selection.Copy
try
wb2.Worksheets("Output").Range("J3:R3").Copy
Also
Instead of
wb.Worksheets("Master").Range("C" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
try
wb.Worksheets("Master").Range("C" & LastCellRowNumber).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Often times, Select creates unexplainable errors. Particularly when working with multiple workbooks, try to stay away from Select. This code comes almost directly from working code I have. Let us know if this doesn't fix the problem.
I re-worked the code and got it working. It's probably not the cleanest way to do it, but given my timeline and lack of VBA knowledge, it will have to do.
Many thanks to engineersmnky for their help.
Description: This code should be put into the worksheet you want to paste content into from another workbook. When it runs it will prompt you to open a workbook to copy from ("Output" worksheet), it will then select the cells you specify in the code (JR:R3), paste them in starting at the next empty row of your initial workbook (finding the last row in column C in the "Master" worksheet), and then it will close & save the workbook you just copied from.
Sub CommandButton1_Click()
'Last cell in column
Dim WS As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long
Set WS = Worksheets("Master")
With WS
Set LastCell = .Cells(.Rows.Count, "C").End(xlUp)
LastCellRowNumber = LastCell.Row + 1
End With
Dim wb As Workbook, wb2 As Workbook
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set selectedworkbook
Set wb2 = ActiveWorkbook
'Select cells to copy
wb2.Worksheets("Output").Range("J3:R3").Select
Selection.Copy
'Go back to original workbook you want to paste into
wb.Activate
'Paste starting at the last empty row
wb.Worksheets("Master").Range("C" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
'Close and save the workbook you copied from
wb2.Save
wb2.Close
End Sub
Have you tried this
Selection.Copy
wb.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial xlPasteValues