Copy data from multiple files into one sheet with incremental rows. - vba

I'm using the following code to open one of multiple files, copy a line from a worksheet, and then paste it back into the first worksheet, then close the opened file.
My problem is I can't get past the function to move down the rows each time it pastes. I want it to incrementally paste the values on the new row, ie. B3, then B4, then B5, etc.
Sub Auto_open_change()
Dim WrkBook As Workbook
Dim StrFileName As String
Dim FileLocnStr As String
Dim LAARNmeWrkbk As String
PERNmeWrkbk = ThisWorkbook.Name
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
Dim StrFile As String
StrFile = Dir(FileLocnStr & "\*.xls")
Do While Len(StrFile) > 0
DoStuff (FileLocnStr & "\" & StrFile)
StrFile = Dir
Loop
End Sub
Private Sub DoStuff(StrFileName)
Workbooks.Open (StrFileName)
Call Edit
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Sub Edit()
Dim Wb1 As Workbook
Dim ws1 As Worksheet
Dim loopcal As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
lngCalc = .Calculation
End With
Set Wb1 = ActiveWorkbook
Sheets("1_3 Octave1 CH1").Select
Range("A3:AH3").Select
Selection.Copy
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B3").Select
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub

You can try this:
Sub GetData(Fname as String)
Dim wb1, wb2 as Workbook
Dim ws1, ws2 as Worksheet
Dim lrow as Long
Set wb1 = Thisworkbook
Set ws1 = wb1.Sheets("DataExtract")
Set wb2 = Worbooks.Open(Fname)
Set ws2 = wb2.Sheets("1_3 Octave1 CH1")
With ws1
lrow = .Range("B" & Rows.Count).End(xlUp).Row
ws2.Range("A3:AH3").Copy
.Range("B" & lrow).Offset(1,0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End With
wb2.Close False
End Sub
Just replace DoStuff and Edit subs.
hope this helps.

Untested:
Sub Auto_open_change()
Dim StrFileName As String
Dim FileLocnStr As String
Dim fNum As Long
Dim StrFile As String
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
fNum = 1
StrFile = Dir(FileLocnStr & "\*.xls")
Do While Len(StrFile) > 0
CopyData FileLocnStr & "\" & StrFile, fNum
StrFile = Dir
fNum = fNum + 1
Loop
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Sub CopyData(StrFileName As String, fNum As Long)
Dim Wb1 As Workbook, rngCopy As Range
Dim rngDest As Range
Set Wb1 = Workbooks.Open(StrFileName)
Set rngCopy = Wb1.Sheets("1_3 Octave1 CH1").Range("A3:AH3")
Set rngDest = ThisWorkbook.Sheets("Data Extract") _
.Range("B2").Offset(fNum, 0)
rngCopy.Copy rngDest
With rngDest.Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
.Value = .Value
End With
Wb1.Close False
End Sub

Well, with the code you're using, you could just create a variable in the Do While Loop that calls DoStuff and pass it through to the Edit sub, then construct the range from that.
So in the Do While Loop
rowcounter = 3
Do While Len(StrFile) > 0
DoStuff (FileLocnStr & "\" & StrFile, rowcounter)
StrFile = Dir
rowcounter = rowcounter + 1
Loop
Then modify DoStuff
Private Sub DoStuff(StrFileName As String, rowcounter As Integer)
Workbooks.Open (StrFileName)
Call Edit(rowcounter)
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Then modify Edit
Sub Edit(rowcounter As Integer)
.
.
.
.
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B" & rowcounter).Select
.
.
End Sub

'Guys, here is the final edit. works perfectly, Thanks for the help and support guys.
Option Explicit
Sub Auto_open_change()
Dim WrkBook As Workbook
Dim StrFileName As String
Dim FileLocnStr As String
Dim LAARNmeWrkbk As String
Dim rowcounter As Integer
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
Dim StrFile As String
StrFile = Dir(FileLocnStr & "\*.xls")
rowcounter = 3
Do While Len(StrFile) > 0
Call DoStuff(FileLocnStr & "\" & StrFile, rowcounter)
StrFile = Dir
rowcounter = rowcounter + 1
Loop
End Sub
Private Sub DoStuff(StrFileName As String, rowcounter As Integer)
Workbooks.Open (StrFileName)
Call Edit(rowcounter)
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Sub Edit(rowcounter As Integer)
Dim Wb1 As Workbook
Dim ws1 As Worksheet
Dim loopcal As Long
With Application
.ScreenUpdating = True
.EnableEvents = True
lngCalc = .Calculation
End With
Set Wb1 = ActiveWorkbook
Sheets("1_3 Octave1 CH1").Select
Range("A3:AH3").Select
Selection.Copy
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B" & rowcounter).Select
'index the variable to ensure the cell reference changes each time.
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub

Related

Paste Special Error - 1004 VBA Excel

I am trying to create a loop to copy data in cells in source worksheet one by one and paste in a particular cell in target worksheet. Once the cell is pasted, i need it to save a copy of the file then paste the next value in the source worksheet.The code is:
Private Sub CommandButton1_Click()
Dim wbTarget As Worksheet
Dim wbSource As Worksheet
Dim SaveLoc As String
Dim FName As String
Dim i As Long
Set wbSource = Sheets("Sheet3")
Set wbTarget = Sheets("Sheet1")
wbSource.Activate
Range("A1").Activate
Do While ActiveCell.Value <> ""
DoEvents
ActiveCell.Copy
For i = 1 To 30
wbTarget.Activate
With ActiveSheet
wbTarget.Range("E5").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths
Selection.PasteSpecial Paste:=xlPasteValues
ThisWorkbook.Save
Application.CutCopyMode = False
End With
SaveLoc = "H:\Services\Test Output\Term_"
FName = Range("B5")
ActiveWorkbook.SaveCopyAs FileName:=SaveLoc & FName & ".xls" 'FileFormat:=xlNormal
Application.DisplayAlerts = False
Next i
wbSource.Select
ActiveCell.Offset(1, 0).Activate
Loop
Application.ScreenUpdating = True
End Sub
When I run this, I get a
run-time error 1004.
Please advise on how to resolve this.
Thank You in Advance.
Try the code below, without using Activate, ActiveCell, Select and Selection, instead use fully qualifies Ranges and Worksheet objects.
Explanation inside the code as comments (also some question about your code).
Code
Option Explicit
Private Sub CommandButton1_Click()
Dim wbTarget As Worksheet
Dim wbSource As Worksheet
Dim SaveLoc As String
Dim FName As String
Dim i As Long, lRow As Long
Set wbSource = Sheets("Sheet3")
Set wbTarget = Sheets("Sheet1")
' SaveLoc string never changes, doesn;t need to be set every time inside the loops
SaveLoc = "H:\Services\Test Output\Term_"
' you never qualifed the range with on of the worksheets (I'm guessing here it's "Sheet3"
FName = wbTarget.Range("B5").Value
Application.ScreenUpdating = False
lRow = 1
Do While wbSource.Range("A" & lRow).Value <> ""
wbSource.Range("A" & lRow).Copy
For i = 1 To 30
' 2 lines below you are pasting to cell "E5" don't you mean to increment with the row number (i variable)
wbTarget.Range("E5").PasteSpecial xlPasteValues
wbTarget.Range("E5").PasteSpecial xlPasteColumnWidths
ThisWorkbook.Save
Application.CutCopyMode = False
' have this line before trying to save a copy of this workbook
Application.DisplayAlerts = False
ThisWorkbook.SaveCopyAs Filename:=SaveLoc & FName & ".xls" 'FileFormat:=xlNormal
Application.DisplayAlerts = True
Next i
lRow = lRow + 1
Loop
Application.ScreenUpdating = True
End Sub

excel cell = filename of another workbook

I have a macro for updating a sheet from another workbook, how can I use that same file to update a cell with its filename without the .xlsx.
Can I use the vFile or wbCopyFrom Dim?
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
If MsgBox("Update Transmission Stock Status data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N3000").ClearContents
Else: Exit Sub
End If
On Error GoTo whoa
'Open file with data to be copied
vFile = "C:\Users\taylorm1\Desktop\OUC\_Materials\Stock Status\Transmission Stock Status*.xlsx"
'vFile = "P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx"
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
'wsCopyFrom.Range("A1:A" & LastRow).Copy
wsCopyTo.Range("B2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
SendKeys "Y"
SendKeys ("{ESC}")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Application.Wait (Now + 0.000005)
Call NoSelect
Exit Sub
Application.ScreenUpdating = True
whoa:
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
'wsCopyFrom.Range("A1:A" & LastRow).Copy
wsCopyTo.Range("B2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
SendKeys "Y"
SendKeys ("{ESC}")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Application.Wait (Now + 0.000005)
Call NoSelect
Exit Sub
'whoa: 'If filename changes then open folder
'Call Shell("explorer.exe" & " " & "P:\ESO\1790-ORL\OUC\_Materials\Stock Status", vbNormalFocus)
End Sub
Thanks
You can get the file's name without path and without extension like this:
Dim s As String
s = Mid(vFile, InStrRev(vFile, "\") + 1)
s = Left$(s, InStrRev(s, ".") - 1)
Or if you want to keep the full path but only remove the extension:
Dim s As String
s = Left(vFile, InStrRev(vFile, ".") - 1)
Then assign it to any cell: myCell.Value = s
Try this code.
Private Sub TestNettFileName()
Debug.Print NettFileName(ThisWorkbook.Name)
End Sub
Private Function NettFileName(Fn As String) As String
Dim Sp() As String
Sp = Split(ActiveWorkbook.Name, ".")
ReDim Preserve Sp(UBound(Sp) - 1)
NettFileName = Join(Sp, ".")
End Function
Use it in your project like,
With ActiveSheet
.Range("A3").Value = NettFileName(.Parent.Name)
End With

update links prompt issue

I have a length code which opens set of files, unhides and navigates to a particular worksheet, copies a range and pastes that range in another workbook.
The problem is whenever the code opens these files a popup message to update links appears. I understand it can be solved with updatelinks = 0 however wanted to know where should i include this in my code.
Also the code takes time to execute, so is there any modifications for faster execution.
Sub mergeallinputworkbooks()
Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String
Dim FolderName As String
Dim oCell As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Master Data")
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
MyPath = FolderName
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls")
Do While Len(MyFile) > 0
Set wkbSource = Workbooks.Open(MyPath & MyFile)
Set wksSource = wkbSource.Worksheets("Scoring DB")
ActiveWorkbook.Unprotect ("pyroo123")
Sheets("Scoring DB").Visible = True
Sheets("Scoring DB").Select
Range("A4:W4").Copy
Windows("Performance Dashboard.xlsm").Activate
With Sheets("Master Data").Range("$A:$A")
With Sheets("Master Data")
Set oCell = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0)
End With
oCell.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Windows("Performance Dashboard.xlsm").Activate
End With
wkbSource.Close savechanges:=False
MyFile = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
For you links issue, have a look at this post. There should be enough information there to give you a good indication of how and where to use the link update.
Now code suggestion:
To improve performance of your code, I would suggest not to interact with worksheet where not necessary. Rather than 'Copy and Past' assign the range to an array:
arrMyRange = Worksheets("SourceWorksheet").Range("A4:W4")
This will create your array. Now assign the array to your location:
Worksheets("DestinationWorksheet").Range("A1").Resize(UBound(arrMyRange, 1), UBound(arrMyRange, 2)).Value = arrMyRange
A1 can be changed dynamically if required.

Excel VBA works only on the last sheet

I have macro below which run an all sheets in workbook and it run through all files in specific directory. But unfortunately it works only for the last sheet in each workbook. It should work for every sheet. Can someone correct my code?
Sub LoopThroughFiles()
Application.ScreenUpdating = False
FolderName = "C:\Users\Karolek\Desktop\E\3\"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
Fname = Dir(FolderName & "*.xls")
'loop through the files
Do While Len(Fname)
With Workbooks.Open(FolderName & Fname)
' here comes the code for the operations on every file the code finds
Call LoopThroughSheets
End With
' go to the next file in the folder
Fname = Dir
Loop
End Sub
Sub LoopThroughSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call naprawa
Next ws
ActiveWorkbook.Close savechanges:=True
End Sub
Sub naprawa()
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long
fndList = Array("Louver-", "Lvrs ", "gauge ", "Galvanized ", "Pieces")
rplcList = Array("Lvr-", "Louvers ", "ga ", "Glvnzd ", "Pcs")
For x = LBound(fndList) To UBound(fndList)
Range("C:C,D:D").Select
Selection.Replace What:=fndList(x), Replacement:=rplcList(x), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next x
End Sub
Why does this need to be in three separate subs? This can be accomplished in a single sub:
Sub LoopThroughFiles()
Dim ws As Worksheet
Dim lCalc As XlCalculation
Dim sFldrPath As String
Dim sFileName As String
Dim aFindList() As String
Dim aRplcList() As String
Dim i As Long
sFldrPath = "C:\Test\"
If Right(sFldrPath, 1) <> Application.PathSeparator Then sFldrPath = sFldrPath & Application.PathSeparator
sFileName = Dir(sFldrPath & "*.xls*")
aFindList = Split("Louver-,Lvrs ,gauge ,Galvanized ,Pieces", ",")
aRplcList = Split("Lvr-,Louvers ,ga ,Glvnzd ,Pcs", ",")
With Application
lCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
On Error GoTo CleanExit
'loop through the files
Do While Len(sFileName) > 0
With Workbooks.Open(sFldrPath & sFileName)
For Each ws In .Sheets
For i = LBound(aFindList) To UBound(aFindList)
ws.Range("C:D").Replace aFindList(i), aRplcList(i), xlPart
Next i
Next ws
.Close True
End With
' go to the next file in the folder
sFileName = Dir
Loop
CleanExit:
With Application
.Calculation = lCalc
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub

Transferring Data from multiple workbooks

Objective - extracting data from multiple workbooks (5 in total); pasting the data into a new workbook.
Problem/Issue:
1) After running the below VBA code it's able to copy data from all the 5 workbooks but while pasting it's pasting data for only one of them.
2) Pop-up window for Clipboard is full. I've written a code to clear the clipboard but it doesn't seem to function as I still get the pop-up window.
VBA Code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim MyPath As String
MyPath = "Directory path"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If MyFile = "filename.xlsb" Then
End If
Workbooks.Open (MyPath & MyFile)
Range("A3:CP10000").Copy
ActiveWorkbook.Close
'calculating the empty row
erow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
a = ActiveWorkbook.Name
b = ActiveSheet.Name
Worksheets("Raw Data").Paste Range("A2")
Application.CutCopyMode = False ' for clearing clipboard
MyFile = Dir
Loop
End Sub
I tried two other commands below as well, but they seem to just return no data at all.
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow + 1, 1), Cells(erow + 1, 30)) `pasting the data`
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("A2")`pasting the data`
Update.
Here is the current code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Users\username\Downloads\PROJECTS\Project Name\Input file\"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If InStr(MyFile, "post_level.xlsb") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
ActiveWindow.Zoom = 90
End Sub
Update2.
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Users\username\Downloads\PROJECTS\ProjectNameFolder\SubFolder\MainFolder\Input file"
MyFile = Dir("C:\Users\username\Downloads\PROJECTS\ProjectNameFolder\SubFolder\MainFolder\Input file\*.*")
Do While Len(MyFile) > 0
If InStr(MyFile, ".csv") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
End Sub
I hope I can help... There are multiple errors in your code, and I am not sure if I fixed them the way you'd want.
It would be useful to mention just one main mistake. You cannot have these 2 lines together:
If MyFile = "filename.xlsb" Then
End If
Between these lines you must put every procedure that you want to do IF he If condition is met. In the original case, if there was a file named "filename.xlsb", nothing would have happened, as you immediately closed the code block...
Try something similar to the following code. It worked for me to import data from all the files in the directory C:\Temp\ which have the extension of .xlsb
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Temp\"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If InStr(MyFile, ".xlsb") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
End Sub