Excel VBA Paste Error "...isn't the same size..." - vba

NB: I'm brand new to VBA and code in general
I've attempted to make a macro that collates data from multiple workbooks and imports it into a master workbook ('ZMaster').
The following code successfully copies data from the cell C5 in multiple workbooks (from file C:\AutoMelinh) and pastes them in a column in my 'ZMaster' workbook.
The issue is I get the error 'The data you are pasting isn't the same size as your selection. Do you want to paste anyway?'. This comes after every paste, so I have to click 'ok' every single time. The format of the cell that is copied, is merged (between C5 and D5). I think this is the issue however I don't know how to mitigate that in the VBA code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("C5").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Loop
End Sub
EDIT: I was able to solve the issue by using
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then
Exit Sub
End If
Application.DisplayAlerts = False
Workbooks.Open (Filepath & MyFile)
Range("C5").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Application.DisplayAlerts = True
Loop
End Sub

you are getting the warning because you are pasting one cell into 4 cells
this should work without using copy/paste
Sub LoopThroughDirectory()
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
Dim MyFile As String
MyFile = Dir(Filepath)
Dim erow As Range
Dim wb As Workbook
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then Exit Sub
Set wb = Workbooks.Open(Filepath & MyFile)
erow = Workbooks("ZMaster.xlsm").Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
erow.Value = wb.Sheets(1).Range("C5").Value
if isempty(erow) then erow.value = "----------"
wb.Close
MyFile = Dir
Loop
End Sub

Related

Unable to Close files which are read using VBA after the operation

Objective: To copy data from all the excel files kept in the folder to the master excel files. The data is being copied correctly. However, I am unable to close all the files which are read by the program. Have tried all these options: ActiveWorkbook.Close, Workbooks(MyFile).Close SaveChanges:=False, Workbooks(MyFile).Close SaveChanges:=False, but none is working.
How to solve the issue?
VBA Code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
MyFile = Dir("C:\Desktop\Actual Files\")
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (MyFile)
Range("A2:O97").Copy
Windows("zmaster.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 15))
Application.ScreenUpdating = False
MyFile = Dir
Loop
End Sub
Creating a workbook variable and using this would be a clean way to do it. The aspects within this sub of activating workbooks and interacting with sheets that aren't fully referenced is a concern and you could improve it further by properly referencing these.
Also be careful with application.screenupdating=false if you disable it within a sub make sure that every exit point will restore it.
Sub LoopThroughDirectory()
Application.ScreenUpdating = False
Dim MyFile As String, wbData As Workbook
Dim erow
MyFile = Dir("C:\Desktop\Actual Files\")
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Application.ScreenUpdating = True
Exit Sub
End If
Set wbData = Workbooks.Open(MyFile)
Range("A2:O97").Copy
Windows("zmaster.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 15))
wbData.Close False
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

Copy spreadsheet from Downloads folder locally into a main sheet on a different spreadsheet

I've hit a roadblock and I can't figure it out for the life of me. Here is what I am trying to accomplish:
A program I use exports a snapshot of the data into a spreadsheet (.xls) into the Downloads folder locally.
I need to copy the data of sheet1 of this spreadsheet (without opening it) into the main spreadsheet I have saved elsewhere which is the "main" sheet and open. I have a macro button on the main sheet that runs this code.
The caveat is that I have to make the Downloads folder dynamic in that it is not a specific username, because it is going to be used by multiple users.
This code works perfectly for 1 person:
Sub sbCopyingAFile()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
MyDir = "C:\Users\{My_Username}\Downloads\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
With Worksheets(1)
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(2, 1), .Cells(Rws, 19))
Rng.Copy Wb.Worksheets("DUMP").Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)
ActiveWorkbook.Close True
End With
MyFile = Dir()
Loop
On Error Resume Next
Kill "C:\Users\{My_Username}\Downloads\*.*"
On Error GoTo 0
End Sub
This was my last attempt at getting any Downloads folder, not specific to a username:
Sub sbCopyingAFile()
Dim MyFile As String, Str As String, Wb As Workbook, MyDir As String
'Dim fso
Dim Rws As Long, Rng As Range
'Set fso = CreateObject("Scripting.FileSystemObject")
Set Wb = ThisWorkbook
MyDir = CreateObject("WScript.Shell").specialfolders("Downloads")
'MyDir = "C:\Users\{My_Username}\Downloads\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
With Worksheets(1)
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(2, 1), .Cells(Rws, 19))
Rng.Copy Wb.Worksheets("DUMP").Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)
ActiveWorkbook.Close True
End With
MyFile = Dir()
Loop
On Error Resume Next
'Kill "C:\Users\{My_Username}\Downloads\*.*"
On Error GoTo 0
End Sub
You can use Environ$("Username") to get the current username. This will return a string.
So your path would look something along the lines of:
"C:\Users\" & Environ$("Username") & "\Downloads\"
You can also use Environ$("UserProfile") & "\Downloads\" in case the user set up their profiles in a weird place that isn't "C:\Users"

Open workbooks in filepath and copy sheet 2 to Masterworkbook

I would like to open all workbooks in a filepath on my hard-drive and then copy table data from sheet 2 to Master workbook with the name of Master.
I found this code and have modified it to suit my needs but I'm stuck.
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMiljö\Prognosverktyg\Sektionsfil\Gruppfiler"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = “master.xlsm” Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Worksheets("FärdigÖnskemål").Range("A4:D4").Select
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("DataÖnskemål").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Loop
End Sub
Any help this friday?
According to your code, it's not clear what Worksheet is the destination sheet (the one you want to paste to), is it Sheet1 or Worksheets("DataÖnskemål").
Anyway, in my code it pastes to Sheet1, let me know if you meant something else.
Code
Option Explicit
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler\"
MyFile = Dir(Filepath)
Do While MyFile <> ""
If Not MyFile Like "master.xlsm" Then
Set wb = Workbooks.Open(Filepath & MyFile)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemål").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
MyFile = Dir()
Loop
End Sub
I would recommend using FileSystemObject instead:
Sub LoopThroughDirectory()
Dim MyFile As File
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Dim FSO As New Scripting.FileSystemObject
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler"
For Each MyFile In FSO.GetFolder(Filepath).Files
If Not MyFile.Name Like "master.xlsm" Then
Debug.Print MyFile.Path
Set wb = Workbooks.Open(MyFile.Path)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemal").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
Next
End Sub
You have to add Microsoft Scripting Runtime reference to your project.
You can read more here

Compare File Date Modified in VBA

So I am writing a code in VBA that opens up all files in a document and copies and pastes the information from each document. The code is set up to open up every document, but itself. My dilemma is that I want the code to open ever document that has been modified after the last day the main file has been modified. Basically I want to compare two dates with one date staying the same and the other changing after every loop (new document every loop). My code is below and any help or suggestion would be much appreciated. Thanks!
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date
Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")
Do While Len(MyFile) > 0
If MyFile = "zmasterfile.xlsm" Then
Exit Sub
If DateReflections < DateMaster Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("B4:N4").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))
MyFile = Dir
Loop
End Sub
You shouldn't be exiting the sub in your if statement. You might consider changing you IF statement to something like below:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date
Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")
Do While Len(MyFile) > 0
DateReflections = FileDateTime(Filepath)
If MyFile <> "zmasterfile.xlsm" and DateReflections > DateMaster Then
Workbooks.Open (Filepath & MyFile)
Range("B4:N4").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))
End If
MyFile = Dir
Loop
End Sub
You just need to reset the DateReflections in your loop, using MyFile to build the file path. See below.
If MyFile = "zmasterfile.xlsm" Then
Exit Sub
DateReflections = FileDateTime(Filepath & "\" & MyFile)
If DateReflections < DateMaster Then
Exit Sub
End If
As an aside, if you'd like to just skip the file and continue processing, rather than exiting the sub entirely, replace your Exit Subs with Continue Do

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