The error occurs on the Open.Workbooks MasterFile line. I get the error of "This file cannot be found. Has it been removed, renamed, or replaced?" I used the fso.FileExist function to make sure the file does actually exist, and when I debug.print, the file name is exactly as it is specified in the variable MasterFile. Why won't VBA recognize this .xlsm file?
Sub ProcessData()
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim fil As Scripting.File
Dim MyDir As String
Dim FolderSource As Scripting.Folder
'FolderSource is the fso enabled directory folder
Dim FolderDataSource As Scripting.Folder
'FolderDest is the fso enabled folder where the MasterFile is located
MyDir = "C:\Users..."
'MyDir is where all part number files will be stored
Dim MasterFile As String
Dim MasterFilePath As String
MasterFilePath = "C:\Users..."
MasterFile = "Function Master File.xlsm"
Dim wbSource As Workbook, wsSource As Worksheet
'The workbook and worksheet source will be the Master FIle
Dim wbDest As Workbook, wsDest As Worksheet
'The destination workbook and worksheet corresponding to the part number file
Dim myArray As Variant
Dim myTable As ListObject
Dim x As Long
myArray = Range("D13:D17")
'Array will draw from part number values that are entered in the appropriate area on the template
'Creating files for all new part numbers
Set FolderSource = fso.GetFolder(MyDir)
'For Each fil In FolderSource.Files
For x = LBound(myArray) To UBound(myArray)
If myArray(x, 1) <> "" Then
PartNumFile = MyDir & "\" & myArray(x, 1) & ".xlsx"
If Not fso.FileExists(PartNumFile) Then
Set newbook = Workbooks.Add
With newbook
.SaveAs Filename:=PartNumFile
End With
End If
End If
'Searching for the Part Number Data in the Master File
Set FolderDataSource = fso.GetFolder(MasterFilePath)
For Each fil In FolderDataSource.Files
Debug.Print fil.Name
If fso.FileExists(MasterFilePath & "\" & MasterFile) Then
Debug.Print fil.Name
Workbooks.Open MasterFile
Set wbSource = Workbooks(MasterFile)
Set wsSource = wbSource.Worksheets(1)
lrSource = wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row
Set wbDest = Workbooks(myArray(x, 1) & ".xlsx")
Set wsDest = wbDest.Worksheets(1)
lrDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1
wsSource.Range("A2:V" & lrSource).Copy Destination:=wsDest.Range("A" & lrDest)
End If
Next
Next
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'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
I'm trying to run macro from file "A: that include Sheet named "Filter_Criteria" on multiple Worksheets from specific folder.
In each "B%" Worksheet from selected folder data from Sheet "Data" shall be filtered by range Sheet "Filter_Criteria" from file A and send back to Sheet "Output" file "B%".
Issue is that non of files from folder is being filtered and I got to results in any "B%" Worksheet.
Macro goes from the beginning to the end with no issues.
Inside-macro code works fine while running it on each file with:
Set Data_sh = ActiveWorkbook.Sheets("Data")
Set Output_sh = ActiveWorkbook.Sheets("Output")
But I cannot understand what is wrong with current changes.
Sub RunOnAllFilesInFolder()
Dim folderName As String, eApp As Excel.Application, fileName As String
Dim wb As Workbook, ws As Worksheet, currWs As Worksheet, currWb As Workbook
Dim fDialog As Object: Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
Dim Filter_Criteria_Sh As Worksheet
Set currWb = ActiveWorkbook: Set currWs = ActiveSheet
Set Filter_Criteria_Sh = ThisWorkbook.Sheets("Filter_Criteria")
'Folder with Worksheets
fDialog.Title = "Select a folder"
fDialog.InitialFileName = currWb.Path
If fDialog.Show = -1 Then
folderName = fDialog.SelectedItems(1)
End If
'New Excel Process
Set eApp = New Excel.Application: eApp.Visible = False
fileName = Dir(folderName & "\*.*")
Do While fileName <> ""
'Update status bar to indicate progress
Application.StatusBar = "Processing " & folderName & "\" & fileName
Set wb = eApp.Workbooks.Open(folderName & "\" & fileName)
'Filter Data Macro
Dim Data_sh As Worksheet
Dim Output_sh As Worksheet
Set Data_sh = wb.Sheets("Data")
Set Output_sh = wb.Sheets("Output")
Output_sh.UsedRange.Clear
Data_sh.AutoFilterMode = False
Dim Emp_list() As String
Dim n As Integer
n = Application.WorksheetFunction.CountA(Filter_Criteria_Sh.Range("A:A")) - 2
ReDim Emp_list(n) As String
Dim i As Integer
For i = 0 To n
Emp_list(i) = Filter_Criteria_Sh.Range("A" & i + 2)
Next i
Data_sh.UsedRange.AutoFilter 2, Emp_list(), xlFilterValues
Data_sh.UsedRange.Copy Output_sh.Range("A1")
Data_sh.AutoFilterMode = False
MsgBox ("Data has been Copied")
wb.Close SaveChanges:=False
Debug.Print "Processed " & folderName & "\" & fileName
fileName = Dir()
Loop
eApp.Quit
Set eApp = Nothing
'Clear statusbar and notify of macro completion
Application.StatusBar = ""
MsgBox "Completed executing macro on all workbooks"
End Sub
I expect that 'Filter Data Macro will filter data in each file with filter criteria stored in Worksheet "A"
wb.Close SaveChanges:=False
You're not saving any changes you make to the workbooks.
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
I am trying to create For Each loop for a several workbooks; however I am not able to set the workbook name in the array and thus resulted into this. I'm stuck in trying to concatenate the workbook name.
Here's my code:
'Open all .csv file in folder location
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(ThisWorkbook.Path)
For Each objFile In objFolder.Files
If InStr(objFile, ".csv") Then
Workbooks.Open (objFile)
End If
Next
' Declare variables
Dim WrkBkPrm As Workbook
Dim WrkBkSrc As Workbook
Dim WrkShtPrm As Worksheet
Dim WrkShtSrc As Worksheet
Dim TextSrc(4) As String
Dim SrcRng As Range
Dim DRng As Range
' Assign values to TextSrc() Array
TextSrc(0) = Cable
TextSrc(1) = Care
TextSrc(2) = MSD
TextSrc(3) = Business
'Set WrkBkPrm and WrkShtPrm values
Set WrkBkPrm = Workbooks("MasterFile" & ".xlsm")
Set WrkShtPrm = WrkBkPrm.Worksheets("Canvas")
'Activate Canvas Sheet
WrkBkPrm.Activate
WrkShtPrm.Select
Application.ScreenUpdating = False
'Start For Each Loop
For Each Src In TextSrc()
Set WrkBkSrc = Workbooks(Src & ".csv")
Set WrkShtSrc = WrkBkSrc.Worksheets(Src)
'Copy loop for 1st section
For i = 2 To 49
For j = 7 To 25
Set SrcRng = WrkShtSrc.Cells(i, j)
Set DRng = WrkShtPrm.Cells(i, j)
If SrcRng <> "" Then
DRng.Value = SrcRng.Value
End If
Next j
Next i
Next Src
Application.ScreenUpdating = True
I'd suggest you work on the file as soon as you get hold of the relevant info you need.
Something like:
Dim wb As Workbook
For Each objFile In objFolder.Files
If InStr(objFile.Name, ".csv") <> 0 Then
Set wb = Workbooks.Open(Thisworkbook.Path & "\" & objFile.Name)
'~~> Do your cool stuff with the opened CSV File
wb.Close False '~~> Close without saving
Set wb = Nothing '~~> Clean up although most of the time not necessary
End If
Next
As for the route you took, for you to use For Each Loop on TxtSrc, you need to declare it as variant.
Something like:
Dim TxtSrc As Variant, Src As Variant
TxtSrc = Array("Cable", "Care", "MSD", "Business")
For Each Src In TxtSrc
Set wb = Workbooks.Open(Thisworkbook.Path & "\" & Src & ".csv")
'~~> More cool stuff here
wb.Close False
Set wb = Nothing
Next
It is important that provide the correct argument for the Workbook Open Method.
You should always include the complete path in string format. HTH.