I've got a loop that will take contents from 3 worksheets in a folder, and paste them onto a different workbook. I'd like to name them all a number. 1, 2, and 3 in the new workbook for use later while manipulating data.
I've tried naming a variable but I can't figure out how to have it increase by 1 each time.
Sub find()
Dim iIndex As Integer
Dim ws As Excel.Worksheet
Dim wb As Workbook
Dim strPath As String
Dim strFile As String
Dim i As Integer
i = 1
strPath = "P:\SD\SUPPORT\File Load\"
strFile = Dir(strPath & "*.xls")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strPath & strFile)
For iIndex = 1 To wb.Worksheets.Count
Set ws = wb.Worksheets(iIndex)
'Copy each worksheet into dual sub workbook
ActiveSheet.Copy After:=Workbooks("Dual Sub.xlsm").Sheets(4)
ActiveSheet.Name = i + 1
Next iIndex
strFile = Dir 'This moves the value of strFile to the next file.
Loop
End Sub
With this code it just names the first sheet '2', and gives an error that it cannot name multiple sheets the same thing. I'd like for each sheet to be named as 1, 2, and 3.
If I understood your logic, this should do the trick:
Option Explicit
Sub find()
Dim ws As Worksheet
Dim wb As Workbook
Dim Masterwb As Workbook
Set Masterwb = Workbooks("Dual Sub.xlsm")
Dim strPath As String
Dim strFile As String
strPath = "P:\SD\SUPPORT\File Load\"
strFile = Dir(strPath & "*.xls")
Dim i As Long
i = i + 1
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strPath & strFile)
For Each ws In wb.Worksheets 'better to loop like this (you loop trhough every item in the workbooks.worksheets collection)
ws.Copy After:=Masterwb.Sheets(Masterwb.Sheets.Count) 'copy the worksheet on the new workbook to the last index on the master workbook
Masterwb.Sheets(Masterwb.Sheets.Count).Name = i 'name the last sheet on the master workbook the value of i starting from 1
i = i + 1
Next ws
strFile = Dir 'This moves the value of strFile to the next file.
Loop
End Sub
Related
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
I need to combine multiple workbook to one workbook.
Source workbooks have unique sheet name = "job"
Destination workbook have multiple sheets name
The Below code have 2 issues,
For loop not work
pasted data in Destination workbook create a new sheet. But i need to paste the data to existing sheet.
Sub combine()
'destination worksheets
Dim Ar As Worksheet
Dim nr As Worksheet
Set Ar = ThisWorkbook.Sheets("sheetAr")
Set nr = ThisWorkbook.Sheets("Sheetnr")
'Source workbooks
Dim FolderPath As String
Dim Filename As String
Application.ScreenUpdating = False
FolderPath = Environ("userprofile" & "\Desktop\Copy")
Filename = Dir(FolderPath & "*.xlsx*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
Dim ws As Worksheet
Dim AW As Workbook
Set AW = ActiveWorkbook
Set ws= ActiveWorkbook.Sheets("Job")
For Each AW In ws
AW.Activate
Cells.ShownAll
ws.Copy Ar
Next AW
Workbooks(Filename).Close savechanges = True
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
FolderPath = Environ("userprofile" & "\Desktop\Copy") should be FolderPath = Environ("userprofile") & "\Desktop\Copy\".For Each AW In ws makes no sense since AW is a workbook and ws a worksheet. You probably meant For Each ws in AW but there is no need to loop if only Job sheet is the source. Workbooks(Filename).Close savechanges = True is missing : but since the workbook was opened read-only there are no change to save so use .Close savechanges := False.
Option Explicit
Sub combine()
Dim wb As Workbook, rng As Range
Dim wsAr As Worksheet, wsSrc As Worksheet
Dim FolderPath As String, Filename As String
Dim iTargetRow As Long, c As Long, n As Long
FolderPath = Environ("userprofile") & "\Desktop\Copy\"
Filename = Dir(FolderPath & "*.xlsx*")
' destination worksheet
Set wsAr = ThisWorkbook.Sheets("sheetAr")
iTargetRow = wsAr.UsedRange.Row + wsAr.UsedRange.Rows.Count
Application.ScreenUpdating = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
Set wsSrc = wb.Sheets("Job")
Set rng = wsSrc.UsedRange
rng.Copy wsAr.Cells(iTargetRow, rng.Column)
iTargetRow = iTargetRow + rng.Rows.Count
wb.Close savechanges:=False ' opened read only
Filename = Dir()
n = n + 1
Loop
Application.ScreenUpdating = True
MsgBox n & " workbooks scanned", vbInformation
End Sub
I have 8 workbooks all with one sheet and I'm trying to import them into one master workbook using VBA. This is the code I'm using, it's my first time using VBA.
Sub ImportStats()
Dim WbDest As Workbook
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim myPath As String
Dim strFileName As String
myPath = ThisWorkbook.path & "\stats\"
Set weDest = ThisWorkbook
strFileName = Dir(myPath)
Do Until strFileName = ""
Set wbSource = Workbooks.Open(Filename:=myPath & "\" & strFileName)
Set wsSource = wbSource.Worksheets(1)
wsSource.Copy after:=WbDest.Worksheets("National2")
wbSource.Close
strFileName = Dir()
Loop
End Sub
Looping Through Files Using Dir
Multiple Issues
'*** is indicating modifications of your code.
Although Dir would accept ThisWorkbook.Path & "\stats\", ThisWorkbook.Path & "\stats" (without the trailing backslash) is sufficient, which will also prevent having a double backslash (wrong) when later building the path with myPath & "\" & strFileName) (indicated in chris neilsen's comment).
Set weDest = ThisWorkbook contains a typo and should be Set wbDest = ThisWorkbook. Using Option Explicit at the beginning of each module, will force you to declare all variables and will 'find' these typos immediately.
In the line CurrentIndex = WbDest.Sheets("National2").Index, we are defining the position of the sheet in the tabs. When using the After argument, then when we add a sheet its index will be by one (1) greater than the index of the specified sheet. When we add another one, its index should be by one (1) greater than the previous one (by two (2) greater than the index of the specified sheet)... hence: CurrentIndex = CurrentIndex + 1.
With SaveChanges:=False in wbSource.Close SaveChanges:=False we are preventing Excel to show us a message (when the worksheet was somehow modified (recalculated)), to ask if the workbook should be saved before closing.
The Code
Option Explicit
Sub ImportStats()
Dim WbDest As Workbook
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim myPath As String
Dim strFileName As String
Dim CurrentIndex As Long '***
myPath = ThisWorkbook.Path & "\stats" '***
Set WbDest = ThisWorkbook '***
CurrentIndex = WbDest.Sheets("National2").Index '***
strFileName = Dir(myPath)
Do Until strFileName = ""
Set wbSource = Workbooks.Open(Filename:=myPath & "\" & strFileName)
Set wsSource = wbSource.Worksheets(1)
wsSource.Copy After:=WbDest.Sheets(CurrentIndex) '***
wbSource.Close SaveChanges:=False '***
CurrentIndex = CurentIndex + 1 ' ***
strFileName = Dir()
Loop
End Sub
I am attempting to consolidate data from multiple workbooks into one Master workbook. All workbooks, including the master workbook, have the same worksheets. The data in the worksheets, however, is different. Each workbook is created from asking the same survey questions. I am looking to consolidate all survey answers into one workbook.
Code:
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim lastRowNumber As Double
Dim lastColumnNumber As Double
Dim theLastCell As String
Dim copyRange As Range
Dim pasteRange As Range
Dim sheetName As String
Dim copyRangeString As String
Dim pasteRangeString As String
Do While myFile <> ""
Set wb = Workbooks.Open(FileName:=myPath & myFile)
DoEvents
wb.Worksheets(1).Range("A2:D2").Interior.color = RGB(51, 98, 174)
For i = 1 To 8
lastRowNumber = lastRowUsed(wb.Sheets(i))
lastColumnNumber = wb.Sheets(i).Range("A1").SpecialCells(xlCellTypeLastCell).Column
theLastCell = Cells(lastRowNumber, lastColumnNumber).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Set copyRange = wb.Worksheets(i).Range("A2:" & theLastCell)
copyRangeString = "A2:" & theLastCell
lastRowNumber = lastRowUsed(theWorkbook.Sheets(i)) + lastRowUsed(wb.Sheets(i))
pasteRangeString = "A" & lastRowNumber & ":" & theLastCell
theWorkbook.Sheets(i).Range(pasteRangeString) = wb.Sheets(i).Range(copyRangeString).value
copyRangeString = ""
pasteRangeString = ""
sheetName = wb.Sheets(i).name
MsgBox sheetName
Next
wb.Close
DoEvents
myFile = dir
Loop
I am trying to accomplish this by looping through each Excel file in a folder, looping through (1-8) of the worksheets. Creating a range of the data in each worksheet, and then copying and pasting into the theWorkbook "master" workbook. For whatever reason, only data from the last workbook in the folder is getting copied.
Any and all help is much appreciated!
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