copying data from another workbook - excel

i am trying to replace the current data in my file with the data in any another selected file which have same attributes. i want to replace the data from A1:Q in the current file from any other selected file. I tried writing the code but its showing errors .
Sub newdata()
Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
'Open Source File.xlsx
With appxl
vFile = Application.GetOpenFilename(Title:="Select File To Be Opened")
If vFile = False Then Exit Sub 'if the user didn't select a file, exit sub
' Set myfile = Workbooks.Open(vFile)
.Visible = False
End With
'Get first sheet data
Set myfile = appxl.Windows(vFile)
myfile.Activate
Set currentSheet = myfile.Sheets(1)
'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
appxl.Workbooks(vFile).Close
End Sub

This is not the prettiest of codes but it works just as you asked!
Sub newdata()
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
Dim sourcefileworksheet As String
Dim destinationwb As String
Dim destinationwksheet As String
'set destination worksheet as open workbook when you run macro
destinationwb = ActiveWorkbook.Name
destinationwksheet = ActiveSheet.Name
'Select source file
Dim fNameAndPath As Variant, wb As Workbook
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
' cancel macro if nothing selected
If fNameAndPath = False Then
MsgBox ("Nothing Selected, Macro Cancelled")
Exit Sub
End If
'Open Source File.xlsx
Workbooks.Open (fNameAndPath)
'set source names
sourceFileName = ActiveWorkbook.Name
sourcefileworksheet = ActiveSheet.Name
'Determine last row of source
lastRow = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1").End(xlDown).Row
'Past the table in my current Excel file - Note that you should change the range of destination to A1:Q if you want all copied
Workbooks(destinationwb).Worksheets(destinationwksheet).Range("A1:E" & lastRow) = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
Workbooks(sourceFileName).Close
'Confirm complete
MsgBox ("Complete!")
End Sub

Related

Column number - copying and pasting from file to another file

I have a little problem with my code. I want to copy my data from one file to my main file. When I check the code I meet with one problem. The code works fine until copied. In this line
Set cell1 = wsDest.Cells(1, Range("B1").End(xlToRight).Column + 1)
the cell is selected from the file from I am taking the data and not the folder I am pasting into.
I want my data to paste from these other files into the main file. I want to add them as columns, not rows.
Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")
mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
strFile = Dir(strFolder & "*.xls*")
Do While strFile <> ""
Set newWb = Workbooks.Open(strFolder & strFile)
Set newWs = newWb.Sheets(1)
strFile = Dir
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
newWs.Columns(ActiveCell.Column).EntireColumn.Delete
newWs.Range("B1", Range("B1").End(xlDown).End(xlToRight)).Copy _
mainWs.Range("P1")
Loop
End Sub
You have to declare which file/sheet is which. Each line should refer to the right worksheet. All lines starting with cell or range should have worksheet first like: "mainWs.Cell".
In the new file you have not declared any worksheet, only workbook (wb).
I haven't tryed the code below, but I hope it unlocks your problem thinking.
Good luck!
Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Dim strFile As String
Dim cell1 As Range
Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")
mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
'in my main file I delete the last column only one
strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
strFile = Dir(strFolder & "*.xls*")
Do While strFile <> ""
Set newWb = Workbooks.Open(strFolder & strFile)
'Set the sheet you want to use, using "first sheet" or sheet by name
'Set newWs = newWb.Sheets(1)
'Set newWs = newWb.Worksheets("Worksheet1")
strFile = Dir
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
newWs.Columns(ActiveCell.Column).EntireColumn.Delete
'Set cell1 = newWs.Cells(1, Range("B1").End(xlToRight).Column + 1)
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Copy
'the adress is taking from file when I take the data, not the main file which should take.
mainWs.Range(cell1).PasteSpecial Paste:=xlPasteValues
Loop
End Sub

Excel VBA - How do copy and transpose paste another sheet

I try to copy data from Workbooks with Sheets("daily shift report") to another Workbooks Sheets ("Sheet1") by transpose according to the code below.
Sub copyDatafrommultipleworkbookintomaster()
Dim FolderPath As String, Filepath As String, Filename As String, Erow As Range
FolderPath = "C:\Users\YIT\Documents\test\April57\"
Filepath = FolderPath & "*.xls*"
Filename = Dir(Filepath)
Do While Filename <> ""
Workbooks.Open (FolderPath & Filename)
ActiveWorkbook.Sheets("daily shift report").Range("B71:G77").Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close
Worksheets("Sheet1").Range("A1").PasteSpecial Transpose:=True
Filename = Dir
Loop
End Sub
But found Run time error '1004' Application-defined or object-defined error.I guess error in line 14.
Worksheets("Sheet1").Range("A1").PasteSpecial Transpose:=True
Could you please suggest a solution to this problem?.
Try the next code, please. It will Paste, from each existing .xls workbook, in the next empty column of "Sheet1":
Sub copyDatafrommultipleworkbookintomaster()
Dim FolderPath As String, Filepath As String, Filename As String
Dim wb As Workbook, ws As Worksheet, Col As Long
Col = 1
Set ws = ActiveWorkbook.Sheets("Sheet1")
FolderPath = "C:\Users\YIT\Documents\test\April57\"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
Set wb = Workbooks.Open(FolderPath & Filename)
wb.Sheets("daily shift report").Range("B71:G77").Copy
ws.cells(1, Col).PasteSpecial Paste:=xlPasteAll, Transpose:=True
Col = Col + 7 'increment the next col where to paste
wb.Close False
Filename = Dir
Loop
End Sub
Please see if either of following two set of codes is useful to you.
Mention your Source File Path & File name directly as string
Sub GetData()
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetSheet As Worksheet, sourceSheet As Worksheet
'targetSheet is Activeworkbook wherein you would want to fetch the data
Set targetSheet = ActiveWorkbook.Worksheets("Sheet1")
'Mention Source-file path & file name between double quotes below
customerFilename = "C:\Users\YIT\Documents\test\April57\Your_File_Name_Here.xls"
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Set sourceSheet = customerWorkbook.Worksheets("daily shift report")
sourceSheet.Range("B71:G77").Copy
'select in which cell you want to paste data
targetSheet.Range("A1").PasteSpecial Transpose:=True
customerWorkbook.Close
End Sub
In this code you will be prompted to select Source File (.xls or .xlsx or .csv), no need to manually write Source Filepath & Filename.
Sub GetData2()
Dim filter As String, caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetSheet As Worksheet, sourceSheet As Worksheet
'targetSheet is Activeworkbook wherein you would want to fetch the data
Set targetSheet = ActiveWorkbook.Worksheets("Sheet1")
'Prompt to get the customerWorkbook i.e. Source Workbook
filter = "Excel and CSV Files (*.xls;*.xlsx;*.csv),*.xls;*.xlsx;*.csv"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Set sourceSheet = customerWorkbook.Worksheets("daily shift report")
sourceSheet.Range("B71:G77").Copy
'select in which cell you want to paste data
targetSheet.Range("A1").PasteSpecial Transpose:=True
customerWorkbook.Close
End Sub
Hope these codes are useful to you. Regards.

Extract All Data from Source Folder

I am attempting to extra data from multiple .xlsm in a folder from a specific cell. The idea is to take a folder that has multiple .xlsm files and extract a specific cell into my current workbook.
See code.
Option Explicit
Const FOLDER_PATH = "C:\Users\maxd\OneDrive - Nortek, Inc\Coil Test Data\coils_35_and_36\36\WET\Testing\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = 7
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
'On Error GoTo errHandler
'Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Sheet1")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xlsm*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets("Summary")
'import the data
With wsTarget
.Range("I" & rowTarget).Value = wsSource.Range("B25").Value
'optional source filename in the last column
.Range("N" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
Actual Results = it does nothing as if there is not a file in the folder.
Expected Results = It will pull the data from cell B25 and insert it to I7 of my current worksheet.
EDIT: When I F8 through the code, it gets to "Set wsSource = wbSource.Worksheets("Summary")" Then I get a runtime error 91

VBA Compile Error, Trying to copy sheet from external file to master file

I am getting a compile error on this code, I am trying to target SourceFileName without opening and load it into my active workbook sheet "data retrieval"
I am getting compile error, sub of function not defined.
Sub test()
Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
 
sourceFileName = "File name"
 
'Open Source File.xlsx
With appxl
    .Workbooks.Open ActiveWorkbook.Path & "\" & sourceFileName
    .Visible = False
End With
  
'Get first sheet data
Set myfile = appxl.Windows(sourceFileName)
myfile.Activate
Set currentSheet = appxl.Sheets(12)
 
'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:E" & lastRow).Value
 
'Close Source File.xlsx
appxl.Workbooks(sourceFileName).Close
End Sub
After applying the below recommendation of Option Explicit and declaring appxl I am getting the following error:
I recommend the following
Option Explicit
Sub test()
Dim AppXl As Excel.Application
Set AppXl = New Excel.Application
AppXl.Visible = False
Dim sourceFileName As String
sourceFileName = "File name"
'Open Source File.xlsx
Dim SourceWb As Workbook 'remember workbook in a variable so we can easily access it
Set SourceWb = AppXl.Workbooks.Open(ThisWorkbook.Path & "\" & sourceFileName)
'Get first sheet data
Dim currentSheet As Worksheet
Set currentSheet = SourceWb.Sheets(12)
'Past the table in my current Excel file
Dim lastRow As Long 'row counting variables MUST be Long
lastRow = currentSheet.Range("A1").End(xlDown).Row
'define the workbook here
ThisWorkbook.Worksheets("Data retrieval").Range("A1:E" & lastRow).Value = currentSheet.Range("A1:E" & lastRow).Value
'Close Source File.xlsx
SourceWb.Close SaveChanges:=False 'close source without saving
AppXl.Quit
End Sub

VBA Save As CSV File is Overwritten by First Sheet

I have workbook, I loop through and save each sheet as a csv. The problem is when the loop finishes Excel prompts me to save. If I click "Save", then last worksheet is overwritten with whichever sheet the excel workbook opens on.
If click "Don't Save" everything remains saved with the proper data, but I can't rely on the user to click "Don't Save" every time so I need to find where my code is over writing the data when saved.
How do I keep my csv sheet from being overwritten?
Sub LipperFormat()
'Create Workbook
Dim wb As Workbook
'Get FilePath
Dim wbActive As Workbook
Set wbActive = ActiveWorkbook
Dim wsActive As Worksheet
Set wsActive = wbActive.Worksheets(1)
'Get File Path
Dim filePath As String
Dim rngActive As Range
Set rngActive = wsActive.Cells(1, 2)
filePath = rngActive.Value
'Open File
Set wb = Workbooks.Open(filePath)
'Create Copy of file and CSV
Dim copyFilePath As String
Dim fileExtension As String: fileExtension = "_OG.xlsx"
copyFilePath = Left(filePath, Len(filePath) - 5) + fileExtension
wb.SaveCopyAs copyFilePath
'Loop through worksheets
Dim WS_Count As Integer
Dim i As Integer
WS_Count = wb.Worksheets.Count
For i = 1 To WS_Count
Dim col As Integer
Dim ws As Worksheet
Set ws = wb.Sheets(i)
'Save As CSV
Dim sheetName As String: sheetName = ws.Name
Dim csvFilePath As String
Dim csvSheet As Worksheet
cvsFilePath = Left(filePath, Len(filePath) - 5) + "__" + sheetName
'ws.Name = sheetName
ws.SaveAs FileName:=cvsFilePath, FileFormat:=xlCSV, CreateBackup:=False
Next i
'wb.Save
wb.Close
End Sub
You code is too large for no benefits. I cleaned it and corrected your mistakes and also added necessary pieces to not ask the users for anything:
Sub LipperFormat()
Dim filePath As String
Dim csvFileName As String
Dim ws As Worksheet
Dim wb As Workbook
Application.DisplayAlerts = False
'define parameters
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1) 'it is better to define it with the name, not with its index
filePath = ws.Cells(1, 2).Value
'Open File
Set wb = Workbooks.Open(Filename:=filePath, ReadOnly:=True)
'loop and save as csv
For Each ws In wb.Worksheets
csvFileName = wb.Path & "\" & Left(wb.Name, Len(wb.Name) - 5) & "__" & ws.Name
ws.Copy
ActiveWorkbook.SaveAs Filename:=csvFileName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next ws
'close WB
wb.Close
Application.DisplayAlerts = True
End Sub

Resources