I need to copy 20+ files, each housed by unique folders, into a single folder. I know this should be fairly simple. I've created the below code but I keep getting a Compile Error: Object required error box. The below code looks sound to me so I'm really struggling to find where the error is.
Folder name is the date of the report (eg. 090118), hence, I decided to use a loop until the end of the month (931). I also added an error handling code so we can skip the holidays and weekends.
Sub CopyFiles()
Dim NewFolder As String
Dim NDay As Long
Dim FileName As String
Dim Month As Variant
Month = InputBox("Enter month, eg. 01-January")
NewFolder = "C:\Results\Trading\2018\" & Month & "\Backtest Daily Files\Daily GS\" 'Don't forget to edit this
NDay = 901
On Error Resume Next
Do While NDay < 931
FileName = Dir("C:\Reports\2018\" & Month & "\0" & NDay & "18\GS_Futures*.cs*")
FileCopy FileName, NewFolder
NDay = NDay + 1
Loop
End Sub
Dir doesn't return the full path. It either returns the file name only if found or a zero-length string if not found. If you want a definitive path and file name reference then you need to prefix the returned string with the folder.
An example would be,
...
Do While NDay < 931
FileName = Dir("C:\Reports\2018\" & Month & "\0" & NDay & "18\GS_Futures*.cs*")
if cbool(len(filename)) then _
FileCopy "C:\Reports\2018\" & Month & "\0" & NDay & "18\" & FileName, NewFolder
NDay = NDay + 1
loop
...
Seems to me that it would be easier to perform a recursive folder search within C:\Reports\2018\ but that's just MO. Relying on a user to type static input like 01-January unerringly is folly.
Found a solution. Needs some tweaking, but I'm all set for now. Thank you to all who took the effort to help. The problem was that I wasn't giving a file name to the destination just the folder (no .csv).
Sub CopyFiles()
Dim NewFolder As String
Dim NDay As Long
Dim FileName As String
Dim Month As String
Month = InputBox("Enter month, eg. 01-January")
NDay = 901
On Error Resume Next
Do While NDay < 931
FileName = "M:\MRL\2018\" & Month & "\0" & NDay & "18\GS_Futures_0" & NDay & "18.csv"
NewFolder = "M:\RMC reports\Trading\2018\" & Month & "\Backtest Daily Files\Daily GS\GS_Futures_0" & NDay & "18.csv"
FileCopy FileName, NewFolder
NDay = NDay + 1
Loop
End Sub
...
Related
Using 2010 Excel VBA - I need to use look up the image/pdf with the Branch Code as a part of its name at "C:\ECB Test\ECB IR COPY" and paste it at "C:\ECB Test\" RO if it exists. If it doesn't, the program needs to highlight the Branch Code.
(File Name Examples: 28-Kochi-ecb-sdwan completed.pdf, 23 eCB Kozhikode completed.pdf/0036.jpeg)
Having done this manually twice for two other excel sheets (4k+ cells), I decided to Frankenstein a module together and, well, it does not work and I have no idea why.
Sub Sort()
Const SRC_PATH As String = "C:\ECB Test\ECB IR COPY"
Const DEST_PATH As String = "C:\ECB Test"
Dim Row_Number As Integer
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Dim Folder_Name As String
Dim Branch_Code As String
Dim Final_Path As Variant
Dim File As String
For Row_Number = 3 To 2465
Branch_Code = Worksheets("WAN RFP").Cells(Row_Number, 2)
Folder_Name = Worksheets("WAN RFP").Cells(Row_Number, 5)
On Error Resume Next
File = Dir(SRC_PATH & "\*" & Branch_Code & "*")
Final_Path = Dir(DEST_PATH & "\" & Folder_Name & "\")
If (Len(File) > 0) Then
Call fso.CopyFile(File, Final_Path)
Else
Cells(Row_Number, 2).Interior.ColorIndex = 6
End If
On Error GoTo 0
DoEvents
Next Row_Number
End Sub
I think its unable to use the Branch Code variable as a wildcard, though I might as well have done something silly somewhere in the code. Can someone please help me out?
The problem is you are using the destination path instead of the source path:
File = Dir(DEST_PATH & "*" & Branch_Code & "*.*")
Change it to
File = Dir(SRC_PATH & "*" & Branch_Code & "*.*")
I have a line of code to open up a workbook based on a dt string that I specify.
Const filename = "Labor_Data_"
Const basepath = "C:\Users\CDL File"
Dim wbPreviousData as workbook
Dim dt As String: dt = Format(DateAdd("m", -1, Now), "mm_yyyy")
and then I open up the previous months file with:
Set wbPreviousData = Workbooks.Open(basepath & "\" & filename & dt & ".xlsx")
But I realize that my company's fiscal calendar can sometimes span 5 weeks, e.g. (last week of March - to - first week of May)
Is there an easy way to update my code to just reference the most recent month that is saved in a file pathway that I specify?
You have to scan all the files in the directory to find the latest
Sub findlatest()
Const filename = "Labor_Data_"
Const basepath = "C:\Users\CDL File"
Dim file As String, absfile As String
Dim latest As String, ts As Double, tsmax As Double
file = Dir(basepath & "\" & filename * "*")
Do While Len(file) > 0
' check timestamp
absfile = basepath & "\" & file
ts = CDbl(FileDateTime(absfile))
If ts > tsmax Then
tsmax = ts
latest = file
End If
file = Dir
Loop
Debug.Print latest
End Sub
I get full path of an Excel file from a cell and use a function to retrieve the file name. I have final result as "abc.xlsx"
I need to insert a time stamp in the file name like "abc_02_11_19.xlsx".
I am able to generate the time stamp, the problem is appending it. The best I could think of was to remove the last five letters from the file name i.e. ".xlsx", append the time stamp and then append the ".xlsx".
The ending might also be ".xlsm", ".xlsb" or ".xls". I would need to extract everything after the dot.
Any better way to do this or if not, how best to do it elegantly?
Snippet of code, I am using-
oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)
newname = FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & " " & oldname
newname = Replace(Replace(Replace(newname, ":", "_"), "/", "_"), "*", "_")
This inserts the time stamp before the file name. I need to append it after.
I've not tested this with your functions as I don't know what they do. But if I'm correct, the FunctionToGetName will return the filename as "filename.extention" and FileDateTime will return the date stamp you wish to attach.
With this you can get the filename by cutting everything after the "." with Left$(filename, InStr(oldname, ".") - 1). Then you can do the reverse of that and add the file extention back with Right$(oldname, Len(oldname) - InStr(oldname, ".")). And as per below, you can put pretty much anything in between.
Sub what()
Dim filename As String
Dim oldname As String
oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)
Newname = Left$(filename, InStr(oldname, ".") - 1) & " " & FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & "." & Right$(oldname, Len(oldname) - InStr(oldname, "."))
End Sub
Check out FSO
Dim fso as object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oldname As String
Dim newname As String
oldname = "abc.xlsx"
newname = fso.GetBaseName(oldname) & "_" & Format(Now(), "mm_dd_yy") & "." & fso.GetExtensionName(oldname)
Debug.Print newname
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object
I have a code that will copy the desired files that I want
here's the code
Dim saveFolder As String
Dim fname As String
saveFolder = "C:\Copied file"
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
FileName = Workbooks("Macros.xlsb").Worksheets("path").Range("B4")
Path = FileName & "\" & folder & "\Samples\*.xlsx"
file = Dir(Path)
Workbooks.Open Path
Sheets("Accounts").copy
ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
Workbooks(file).Close
ActiveWorkbook.Close
it works well but I need to input manually the folder name in the cell column. But I'm clicking every after the macro is done for 1 folder only and so on.
I just want to know how to loop it.
this will be my worksheet(folder) for the folder names:
FOLDER
45
118
180
290
I want to loop the macro for each cells. so that I don't need to click/edit one by one the values. because the folder names can be changed momentarily.
Within the bounds of your question asking for a loop, you can try this ...
Dim saveFolder As String
Dim fname As String
Dim lastRow As Long
Dim i As Long
' Set this either statically or dynamically.
lastRow = 100
saveFolder = "C:\Copied file"
' Start from where you want either statically or dynamically.
For i = 4 To lastRow
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
Filename = Workbooks("Macros.xlsb").Worksheets("path").Range("B" & i)
Path = Filename & "\" & folder & "\Samples\*.xlsx"
file = Dir(Path)
Workbooks.Open Path
Sheets("Accounts").Copy
ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
Workbooks(file).Close
Next
ActiveWorkbook.Close
for just copying files from one location to another, you do not need to open and saveAs on file :)
You can loop in folder names from top row to lastRow and process the folders one by one.
Find last row by
lastRow = wb.sheets("Folder").cells(wb.rows.count, 1).end(xlup).row
Now, loop through the folder name by for loop
for i=2 to lastRow
you can have your folder inside the loop like
for i=2 to lastRow
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A" & i)
...
copy operations and filter here
...
next i
I'm trying to save excel file into a specific path.
So basically, when I click the button, I'm creating a folder, and want to save the file inside that folder.
The created folder has the current month as name. I'm trying to save into that current month folder.
'Create folder as Month Name. Save filename as date inside "month".
Dim sDate As String = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String = DateTime.Now.ToString("MMMM")
Dim sFolder = Application.StartupPath & "\Resources\Excel\"
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
Dim sfinal = Path.Combine(sFolder, sMonth)
xlSh.SaveAs(sfinal & Format(sDate) & ".xlsx")
xlApp.Workbooks.Close()
xlApp.Quit()
As it is, this code doesn't give me any errors. But instead of creating a folder named "March" <-current month and saving inside it, it saves the file in \Excel\ and it also creates folder in the same place.
you could use the following function (similar to .NET System.IO.Path.Combine)
Function PathCombine(path1 As String, path2 As String)
Dim combined As String
combined = path1
If Right$(path1, 1) <> Application.PathSeparator Then
combined = combined & Application.PathSeparator
End If
combined = combined & path2
PathCombine = combined
End Function
Hope this helps!
After long hours of excruciating pain, I've finally did it!
Apparently I was missing an "\"
Since "sMonth" became dynamic name, which later I wanted to use as path, and save files in that folder. I needed to simply put that "\" after sMonth, to tell it to save inside it.
Before I realize this... I've broken down, simplified the code as much as I could so I can logically connect the pieces. What I ended up with, is something slightly different. Now the SaveAS properly saves the file inside the new folder.
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
Dim sFileName As String
sFileName = sDate + ".xlsx"
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
Dim sfinal As String
sfinal = (sFolder & sMonth & "\") '<- this thingie here o.O
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
xlSh.SaveAs(sfinal & Format(sFileName))
xlApp.Workbooks.Close()
xlApp.Quit()
Thanks for the help.
You don't appear to actually be setting the save path to the created directory. Instead, I believe you're appending the month to the beginning of the file name in the xlSh.SaveAs(sFinal & Format(sDate) & ".xlsx"). Basically (though I'm not sure of the specific command) you need to navigate to the folder you created after you create it. Probably something to the format of
My.Computer.FileSystem.ChangeDirectory(sFolder & Format(sMonth))
though I don't know that that specific command actually exists as I wrote it.
To those who have been wondering wtf I was doing with all this, here is the full sub. And if anyone needs something similar. Thanks for the support. Problem has been resolved.
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Workbooks.Add()
xlSh = xlApp.Workbooks(1).Worksheets(1)
'Items from listbox1 to be exported into excel, second row, second column.
Dim row As Integer = 2
Dim col As Integer = 2
For i As Integer = 0 To ListBox1.Items.Count - 1
xlSh.Cells(row, col) = ListBox1.Items(i)
row = row + 1
Next
row += 1
col = 1
'Items from listbox2 to be exported into excel, second row, third column.
Dim row2 As Integer = 2
Dim col2 As Integer = 3
For i As Integer = 0 To ListBox2.Items.Count - 1
xlSh.Cells(row2, col2) = ListBox2.Items(i)
row2 = row2 + 1
Next
row2 += 1
col2 = 1
'Create folder as Month Name. Save filename as date inside that folder.
'Make filename be yyyy-MM-DD_HH-mm-ss
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
'This will be used as name for the new folder.
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
'Filename + extension.
Dim sFileName As String
sFileName = sDate + ".xlsx"
'This is the path.
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
'This is the path combined with sMonth to make the final path.
Dim sfinal As String
sfinal = (sFolder & sMonth & "\")
'Check if folder with the name sMonth already exists.
If Dir(sFolder, vbDirectory) = sMonth Then
'If it exist, then simply save the file inside the folder.
xlSh.SaveAs(sfinal & Format(sFileName))
Else
'If it doesn't exist:
'This is the creation of sMonth folder, inside "\excel\.
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
'This saves the excel file at path sfinal, with filename of sFileName
xlSh.SaveAs(sfinal & Format(sFileName))
End If
'Close everything.
xlApp.Workbooks.Close()
xlApp.Quit()
End Sub
I find this method to be much easier.
Create a FileSystemObject and use BuildPath Method, like so:
Set fs = CreateObject("Scripting.FileSystemObject")
skPath = fs.BuildPath(ActiveDocument.Path, "Survival Story of Sword King")
Attention: ActiveDocument.Path is current directory in Word and does not work in excel or other. for excel it would be ActiveWorkbook.Path
My point is some methods or namespace are application specific.