Copy data from one workbook to another - excel

I have looked through this website and got a code similar to this.
My problem is that the code is opening the files but not pasting the data.
The workbook where I am trying to paste the data is TRY 5.xlsm and the range where I am pasting is B3. I am copying the data from workbook Copy of BAFD.xlsx and the range is V1:AF1.
Sub CopyData()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set wb1 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Copy of BAFD.xlsx")
Set wb2 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Practise\TRY 5.xlsm")
Set ws1 = wb1.Sheets("Calib_30Nov")
Set ws2 = wb2.Sheets("Calib29_30")
With ws1.Range("V1:AF1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ws2.Range("B3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
End Sub

You don't need to select anything or use that With statement - does this work?
Sub CopyData()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set wb1 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Copy of BAFD.xlsx")
Set wb2 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Practise\TRY 5.xlsm")
Set ws1 = wb1.Sheets("Calib_30Nov")
Set ws2 = wb2.Sheets("Calib29_30")
ws1.Range("V1:AF1", ws1.Range("V1:AF1").End(xlDown)).Copy
ws2.Range("B3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
EDIT: OK let's take a different approach, we'll define 2 range objects and transfer the values programatically rather than using Copy / Paste:
Sub CopyData()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rngCopy As Range, rngPaste As Range
Set wb1 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Copy of BAFD.xlsx")
Set wb2 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Practise\TRY 5.xlsm")
Set ws1 = wb1.Sheets("Calib_30Nov")
Set ws2 = wb2.Sheets("Calib29_30")
Set rngCopy = ws1.Range("V1:AF1", ws1.Range("V1:AF1").End(xlDown))
Set rngPaste = ws2.Range("B3").Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
rngPaste.Value = rngCopy.Value
End Sub
EDIT - This should now work through the sheets and copy the data across for each one:
Sub CopyData()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rngCopy As Range, rngPaste As Range
Dim strWs1 As String, strWs2 As String, i As Integer, arrSheets() As String
Dim blnExists1 As Boolean, blnExists2 As Boolean
Set wb1 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Copy of BAFD.xlsx")
Set wb2 = Workbooks.Open("C:\Documents and Settings\43707844\Desktop\Change of weights\Svar\BAFD\Practise\TRY 5.xlsm")
'Put all BAFD.xlsx worksheet names into a string array so we can check that they exist
ReDim arrSheets(wb1.Worksheets.Count)
For i = 1 To wb1.Worksheets.Count
arrSheets(i) = wb1.Worksheets(i).Name
Next
'Loop through all sheets in TRY 5, identify numbers and transfer data across
For Each ws2 In wb2.Worksheets
Debug.Print "WS2 Name: " & ws2.Name
strWs1 = Mid(ws2.Name, 5, 2)
strWs2 = Mid(ws2.Name, 8, 2)
Debug.Print "WS2 1 Number: " & strWs1
Debug.Print "WS2 2 Number: " & strWs2
blnExists1 = False
blnExists2 = False
'Check that sheets exist in BAFD.xlsx
For i = LBound(arrSheets) To UBound(arrSheets)
If arrSheets(i) = "Calib_" & strWs1 Then blnExists1 = True
If arrSheets(i) = "Calib_" & strWs2 Then blnExists2 = True
Next
Debug.Print "WS1 Exists: " & blnExists1
Debug.Print "WS2 Exists: " & blnExists2
'If both exist, copy the values across. If they don't, move on to the next one
If blnExists1 = True And blnExists2 = True Then
'Get first sheet details
Set ws1 = wb1.Sheets("Calib_" & strWs1)
Set rngCopy = ws1.Range("V1:AF1", ws1.Range("V1:AF1").End(xlDown))
Set rngPaste = ws2.Range("B3").Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
rngPaste.Value = rngCopy.Value
'Get second sheet details
Set ws1 = wb1.Sheets("Calib_" & strWs2)
Set rngCopy = ws1.Range("V1:AF1", ws1.Range("V1:AF1").End(xlDown))
Set rngPaste = ws2.Range("N3").Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
rngPaste.Value = rngCopy.Value
End If
Next
End Sub

Related

VBA Set Object within If Statement

So, I created a series of formula on a sheet called Extractor in a workbook called "Processor*". The filename of the workbook "Processor*" will usually vary, having other characters to the right of it. My intention is to copy the range covering all formula I created in a sheet named "Extractor" of the workbook "Processor*", and paste to another workbook "INJ*", with a filename also having variable characters to the right, and specifically to the worksheet named "Table". Upon pasting these formula, it will give results of the different cells i need from "INJ*" based on some conditions I already set in my formula. Please, note that the formula works fine when I do the copy and paste myself. Then I want to copy these results to another sheet on the "Processor*". A sheet called "calculation".
Below is the code I wrote, but I can't seem to get the object defined within the IF statement to work outside the statement. I have several of these files to work with, I will really appreciate your help. Thank you!
Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet, lrow As Long, lrow2 As Long, rng As Range
Dim Ct As Long
For Each WB In Application.Workbooks
wb1 = Null
If WB.Name Like "Processor*" Then
Ct = Ct + 1
WB.Activate
Set wb1 = ActiveWorkbook
Set sh1 = wb1.Sheets("Extractor")
Set sh2 = wb1.Sheets("calculation")
Exit For
End If
Next WB
If Ct = 0 Then MsgBox "File not open"
Dim Ct2 As Long
For Each WB In Application.Workbooks
If WB.Name Like "INJ*" Then
Ct2 = Ct2 + 1
WB.Activate
Set wb2 = ActiveWorkbook
Set sh3 = wb2.Sheets("Manager Report")
Set sh4 = wb2.Sheets("TABLE")
Exit For
End If
Next WB
If Ct2 = 0 Then MsgBox "File not open"
With wb1
sh1.Range("C38:J42").Copy wb2.sh4.Range("C38")
End With
With sh4
.Range("C42:J42").Copy
sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End With
Dim wbProc As Workbook, wbInj As Workbook, sh1 As Worksheet
Dim sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet
Set wbProc = WorkbookByName("Proc*")
Set wbInj = WorkbookByName("INJ*")
If wbProc is nothing or wbInj is nothing then
msgbox "missing workbook(s)!"
end if
Set sh1 = wbProc.Sheets("Extractor")
Set sh2 = wbProc.Sheets("calculation")
Set sh3 = wbInj.Sheets("Manager Report")
Set sh4 = wbInj.Sheets("TABLE")
sh1.Range("C38:J42").Copy sh4.Range("C38")
sh4.Range("C42:J42").Copy
sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'....
'....
Function used above:
'get an open workbook by [partial] name
Function WorkbookByName(nm As String) As Workbook
Dim WB As Workbook
For Each WB In Application.Workbooks
If WB.Name Like nm Then
Set WorkbookByName = WB
Exit Function
End If
Next WB
End Function
EDIT: you need to specify which workbook to look at for the sheet
Function WorksheetByName(wb As Workbook, nm As String) As Worksheet
Dim sh As Worksheet
For Each sh In wb.Worksheets '<<<
If sh.Name Like nm Then
Set WorksheetByName = sh
Exit Function
End If
Next sh
End Function
Then:
Set sh4 = WorksheetByName(wbInj, "TABLE*")
Try this
Dim wb1 As Workbook, wb2 As Workbook
Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet
Dim lrow As Long, lrow2 As Long, rng As Range
For Each wb In Application.Workbooks
If wb.Name Like "Processor*" Then
Set wb1 = wb
Set sh1 = wb1.Sheets("Extractor")
Set sh2 = wb1.Sheets("calculation")
Exit For
End If
Next wb
If wb1 Is Nothing Then
MsgBox "File not open"
Exit Sub
End If
For Each wb In Application.Workbooks
If wb.Name Like "INJ*" Then
Set wb2 = wb
Set sh3 = wb2.Sheets("Manager Report")
Set sh4 = wb2.Sheets("TABLE")
Exit For
End If
Next wb
If wb2 Is Nothing Then
MsgBox "File not open"
Exit Sub
End If
sh1.Range("C38:J42").Copy sh4.Range("C38")
sh4.Range("C42:J42").Copy
'''''''''sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
lrow2 does not have a value!!!

Problem with workbook not being dimmensioned

I'm trying to copy the formatting from specific workbook sheets from one workbook V0 then loop through a folder and paste the formatting to other workbooks.
The issue I'm having is the when I try set ws1 as one of the source sheets I get an object undefined error. The ws1 is defined at the top. When I run the code through debug all the other variables the function calls are fine and they were defined the same way.
Dim StrFile As String, SDir As String
Dim name As String
Dim Src_pg1 As String, Src_pg2 As String 'Source and Target sheets
Dim Trgt_pg1 As String, Trgt_pg2 As String
Dim ws1 As Worksheet, ws2 As Worksheet 'define worksheets
Dim ws3 As Worksheet, ws4 As Worksheet
Dim WshSource As Workbook
Dim WshTarget As Workbook
SDir = "dircectory"
StrFile = Dir(SDir + "\*")
Src_pg1 = "Homepage Update"
Trgt_pg1 = "Homepage"
Src_pg2 = "raw"
Trgt_pg2 = "sample"
Application.ScreenUpdating = False
Do While Len(StrFile) > 0
name = StrFile
Set WshSource = Workbooks.Open("directory\v0.xlsm", True, True)
Set WshTarget = Workbooks.Open(SDir + "\" + name, True, True)
Set ws1 = WshSource.Sheets(Src_pg1) '******* Where the error happens****
Set ws2 = WshTarget.Sheets(Trgt_pg1)
Set ws3 = WshSource.Sheets(Src_pg2)
Set ws4 = WshTarget.Sheets(Trgt_pg2)
ws1.Cells.Copy
ws2.Cells.PasteSpecial Paste:=xlPasteFormats 'Source format pasted
ws2.Cells.PasteSpecial Paste:=xlPasteComments 'Comments are pasted.
ws2.Cells.PasteSpecial Paste:=xlPasteValidation 'Validations are pasted
Application.CutCopyMode = False
'Application.Goto .Cells(1), 1
ws3.Cells.Copy
ws4.Cells.PasteSpecial Paste:=xlPasteFormats 'Source format pasted
ws4.Cells.PasteSpecial Paste:=xlPasteComments 'Comments are pasted.
ws4.Cells.PasteSpecial Paste:=xlPasteValidation 'Validations are pasted
Application.CutCopyMode = False
'Application.Goto .Cells(1), 1

Paste from advanced filter

I am stuck on a line and don´t know how to solve the error. I´m dividing the lines in a list by filtering different names with an advanced filter and copying the data in individual sheets, but got stuck on a line, the last one before the Next: "newWS.Range("A1").Paste". I get error 1004 from debugging:
Private Sub loopfilter()
Dim thisWB As Workbook
Dim filterws As Worksheet
Dim howto As Worksheet
Dim advfilter As Range
Dim Postenws As Worksheet
Dim VersandRange As Range
Dim rng As Range
Dim Name As String
Set thisWB = ThisWorkbook
Set filterws = thisWB.Sheets("Filtro")
Set howto = thisWB.Sheets("How to")
Set advfilter = filterws.Range("A1:AK2")
Set Postenws = thisWB.Sheets("Alle gemahnten Posten (2)")
Set VersandRange = howto.Range("J2", Cells(Rows.Count, "j").End(xlUp))
Dim newWS As Worksheet
For Each rng In VersandRange
filterws.Range("AK2") = rng.Value
Application.CutCopyMode = False
Postenws.Range("A1").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=advfilter, _
CopyToRange:=filterws.Range("A5"), _
Unique:=False
filterws.Range("a5").CurrentRegion.Copy
Set newWS = thisWB.Sheets.Add
newWS.Name = rng.Value
newWS.Range("A1").Paste
Next
End Sub
Any idea why its not working?
Thanks
Try this (also made a sheet reference to your definition of Versandrange). Paste is not a method of the range object.
Private Sub loopfilter()
Dim thisWB As Workbook
Dim filterws As Worksheet
Dim howto As Worksheet
Dim advfilter As Range
Dim Postenws As Worksheet
Dim VersandRange As Range
Dim rng As Range
Dim Name As String
Set thisWB = ThisWorkbook
Set filterws = thisWB.Sheets("Filtro")
Set howto = thisWB.Sheets("How to")
Set advfilter = filterws.Range("A1:AK2")
Set Postenws = thisWB.Sheets("Alle gemahnten Posten (2)")
Set VersandRange = howto.Range("J2", howto.Cells(Rows.Count, "j").End(xlUp))
Dim newWS As Worksheet
For Each rng In VersandRange
filterws.Range("AK2").value = rng.Value
Application.CutCopyMode = False
Postenws.Range("A1").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=advfilter, _
CopyToRange:=filterws.Range("A5"), _
Unique:=False
Set newWS = thisWB.Sheets.Add
newWS.Name = rng.Value
filterws.Range("a5").CurrentRegion.Copy newWS.Range("A1")
filterws.Range("a5").CurrentRegion.clearcontents
Next
End Sub

VBA - Copying and Pasting from Multiple Excel files to Single Excel File

Long time reader and admirer of StackOverflow.
Basically I am trying to to loop through a series of Excel files to copy a range of data and paste it on a single Excel workbook/sheet.
The cell range location (C3:D8, D3:E8) is not always consistent, but the table dimensions are: 29 R x 2 C. Also, the files only have 1 sheet, and aside from the table dimensions specified, no data values in other cells.
In its current form the code is executing, but not pasting anything to its destination Excel file.
I need it to
Find the data dimension in file (table)
Copy the table
Paste to destination (below previous table)
Loop through to next file
Repeat Step 1-4
The code is from:
Excel VBA: automating copying ranges from different workbooks into one final destination sheet?
Thanks a lot for any help, I really appreciate it and please feel tell me to specify anything if my question is vague.
Sub SourcetoDest()
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sDestPath As String
Dim sSourcePath As String
Dim shDest As Worksheet
Dim rDest As Range
Dim vaFiles As Variant
Dim i As Long
'array of folder names under sDestPath
'array of file names under vaFiles
vaFiles = Array("Book1.xls")
sDestPath = "C:\Users"
sSourcePath = "C:\Users"
Set wbDest = Workbooks.Open(sDestPath & "\" & "Book2.xlsm")
Set shDest = wbDest.Sheets(1)
'loop through the files
For i = LBound(vaFiles) To UBound(vaFiles)
'open the source
Set wbSource = Workbooks.Open(sSourcePath & "\" & vaFiles(i))
'find the next cell in col C
Set rDest = shDest.Cells(shDest.Rows.Count, 3).End(xlUp).Offset(1, 0)
'write the values from source into destination
rDest.Resize(5, 1).Value = wbSource.Sheets(1).Range("C7:D33").Value
wbSource.Close False
Next i
End Sub
The below should achieve what you're after.
Option Explicit
Sub copy_rng()
Dim wb As Workbook, wbDest As Workbook, ws As Worksheet, wsDest As Worksheet, wsSrc As Worksheet
Dim wbNames() As Variant
Dim destFirstCell As Range
Dim destColStart As Integer, destRowStart As Long, i As Byte
Dim destPath As String
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1") ' Amend to your sheet name
Set wsSrc = wb.Sheets("Sheet2") ' Amend to sheet name with table data
wbNames = ws.Range("A2:A" & lrow(1, ws)) ' Pass col number into lrow function
destPath = "C:\Users\"
Application.ScreenUpdating = False
For i = 1 To UBound(wbNames, 1)
Set wbDest = Workbooks.Open(destPath & wbNames(i, 1))
Set wsDest = wbDest.Worksheets(1)
With wsDest
Set destFirstCell = .Cells.Find(What:="*")
destColStart = destFirstCell.Column
destRowStart = destFirstCell.Row
.Range(Cells(destRowStart, destColStart), _
Cells(lrow(destColStart, wsDest), icol(destRowStart, wsDest))).Copy
End With
wsSrc.Cells(lrow(1, wsSrc) + 1, 1).PasteSpecial Paste:=xlPasteAll
wbDest.Close False
Next i
Application.ScreenUpdating = True
End Sub
Function lrow(ByVal col_num As Integer, sheet_name As Worksheet) As Long
lrow = sheet_name.Cells(Rows.Count, col_num).End(xlUp).Row
End Function
Function icol(ByVal row_num As Long, sheet_name As Worksheet) As Integer
icol = sheet_name.Cells(row_num, Columns.Count).End(xlToLeft).Column
End Function
Ensure you copy both of the functions across, they're used to create the dimensions of the table, and then copying the table.
You will need to amend the sheet name variables. Let me know if you have any questions.
You need to amend the range of where the workbook names are stored. You need to pass the column number in, so that the last row can be calculated. You can also amend the column in which data is pasted back into the workbook.
With the help of this code you can copy all workbooks and worksheets data
into one workbook
Sub copydata()
Dim fso As Scripting.FileSystemObject
Dim fill As Scripting.File
Dim oldfolder As String
Dim newfolder As String
Dim subfolder As Folder
Dim myfolder As Folder
Dim fd As FileDialog
Dim loopcount As Integer
Dim wb
Dim wb2 As Workbook
Dim rr As Range
Set fso = New Scripting.FileSystemObject
Set wb = ThisWorkbook
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
fd.Title = "Please Select Folder to copy"
fd.ButtonName = "Go!"
fd.Show
oldfolder = fd.SelectedItems(1)
Set myfolder = fso.GetFolder(oldfolder)
'Application.ScreenUpdating = False
Application.EnableEvents = False
For Each subfolder In myfolder.SubFolders
For Each fill In subfolder.Files
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill,0 , True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A1:Z300").Copy 'Replace your range
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Next subfolder
MsgBox "Done"
For Each fill In myfolder.Files
Application.DisplayAlerts = False
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Or fill Like "*.xlsb" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill, 0, True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A:Z").EntireColumn.Hidden = False
Range("A1:Z1").AutoFilter
Range("A1:Z300").Copy
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Application.EnableEvents = True
End Sub

Excel VBA to copy column to existing workbook

I have Workbook, source.xlsm, Worksheet "test1" Column A6:A20 that I need to copy to another WorkBook located on my C:... named dest.xlsx, Worksheet "Assets", Column "I". I need to be able to copy the data and be able to add to the column without overwriting the previous data copied. Any help would be a life saver.
Sub Align()
Dim TargetSh As String
TargetSh = "Assets"
For Each WSheet In Application.Worksheets
If WSheet.Name <> TargetSh Then
WSheet.Select
Range("A6:A20").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Sheets(TargetSh).Select
lastRow = Range("I65532").End(xlUp).Row
Cells(lastRow + 1, 1).Select
ActiveSheet.Paste
End If
Next WSheet
End Sub
Is this what you are trying? I have not tested it but I think it should work. Let me know if you get any errors.
Sub Sample_Copy()
Dim wb As Workbook, wbTemp As Workbook
Dim ws As Worksheet, wsTemp As Worksheet
Dim lastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("test1")
'~~> Change path as applicable
Set wbTemp = Workbooks.Open("C:\dest.xlsx")
Set wsTemp = wbTemp.Sheets("Assets")
lastRow = wsTemp.Range("I" & Rows.Count).End(xlUp).Row + 1
ws.Range("A6:A20").Copy wsTemp.Range("I" & lastRow)
Application.CutCopyMode = False
'~~> Cleanup
wbTemp.Close savechanges:=True
Set wb = Nothing: Set wbTemp = Nothing
Set ws = Nothing: Set wsTemp = Nothing
End Sub
HTH
Sid

Resources