VBA dir() returns empty string - vba

I'm trying to get this vba working. It reads the correct filestructure and it does find the first .xlsx and it import the needed data to the control.xlsm.
I notice that after it gets to fileName = dir() the fileName becomes empty. I read that it does this because it cannot find files that match the criteria, but what am i doing wrong?
Here is the code
Sub test_werk_final()
Application.ScreenUpdating = False
Application.CutCopyMode = False
Application.DisplayAlerts = False
Dim directory, fileName As String, sheet As Worksheet
directory = ThisWorkbook.Path & "\"
fileName = Dir(directory & "*.xlsx")
controlFile = Dir(directory & "control.xlsm")
lijn = 2
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
Do Until fileName = ""
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
Workbooks.Open fileName:=(directory & fileName)
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
naam = Sheets("Sheet2").Range("A1").Value
leeftijd = Sheets("Sheet2").Range("A2").Value
Workbooks(controlFile).Worksheets("control").Cells(lijn, 1) = naam
Workbooks(controlFile).Worksheets("control").Cells(lijn, 2) = leeftijd
For Each sheet In Workbooks(fileName).Worksheets
naam = Workbooks(fileName).Worksheets.Range("A1").Value
leeftijd = Workbooks(fileName).Worksheets.Range("A2").Value
Workbooks(controlFile).Worksheets("control").Cells(lijn, 1) = naam
Workbooks(controlFile).Worksheets("control").Cells(lijn, 2) = leeftijd
Next sheet
Workbooks(fileName).Close
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
lijn = lijn + 1
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
fileName = Dir() ' volgende
MsgBox "1" & directory & "2" & fileName & "3" & controlFile
Loop
Application.ScreenUpdating = True
I'm not an expert coding guru, but i do posses basic programming skills.
P.S: i already looked for the questone on differnt fora en didn't find anything that could help me. Maybe i used the wrong search string.
Thanks in advance

You should simple change the order of the two Dir-statements:
controlFile = Dir(directory & "control.xlsm")
fileName = Dir(directory & "*.xlsx")
When you issue a Dir-command with parameter, a new search is started according to the pattern you pass. Dir-command without parameter fetches the next file matching that pattern. In your code, you started first a search with wildcards and then a second search with a fixed filename. When you start your loop, the dir-command will try to find another file with name control.xlsm and of course fails.

Related

Wildcard for file path for adding attachments

I want to add attachments from a specific folder. I specified the file's path and two keywords which are fixed.
There are more characters to complete the file path after 'filename2' and before 'pmonth' which are not fixed and hence I need to use wildcard (*).
The code gives
'Couldn't find file'
I have gone through various threads and tried solutions. None works for what I want.
For ctr = 2 To lastrow
filename1 = Cells(ctr, 1).Value
filename2 = Cells(ctr, 3).Value
Set OutMail = OutApp.CreateItemFromTemplate(str_template)
path = "C:\Users\nikunj.v.tripathi\Desktop\" & filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
With OutMail
.Attachments.Add path ' <----- this line gives error
.To = Cells(ctr, 10).Value
.cc = Cells(ctr, 11).Value
.htmlbody = Replace(.htmlbody, "#Month#", smonth)
.htmlbody = Replace(.htmlbody, "#CLIENT NAME#", Cells(ctr, 1).Value
.Save
End With
Next ctr
To use the Dir function effectively in this case, you'll need the path and the file name as two separate variables. Assuming you add another variable called filename, you could then utilise the following code...
...
path = "C:\Users\nikunj.v.tripathi\Desktop\"
filename = filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
...
filename = Dir(path & filename) ' Dir returns the filename of the first file matching
' the criteria, or returns an empty string if no match.
Do Until filename = ""
.Attachments.Add path & filename
filename = Dir ' Using Dir again returns the next file matching
' the criteria, or returns an empty string if no match.
Loop
Of course - Attachments.Add adds a single attachment and returns the Attachment object. How can it possibly add multiple attachments?
You can use Scripting.FileSystemObject to loop through all files in a folder and add one attachment at a time. See, for example
https://devblogs.microsoft.com/scripting/how-can-i-get-a-list-of-all-the-files-in-a-folder-and-its-subfolders/

VBA:adding files with new version _vX, with separate dates

I am having trouble with creating new version, with the dates selected by the users.
So here I have 2 separate workbooks:
1) Macro - where the users will click the button and generate the macro
2) Report template - when the users click the macro, the figures will be generated into the templates, with the dates in the naming convention, and the version.
The report template naming convention looks like this : BSLCT_DDMMYYYYG where DDMMYYYY is the date, that the users will select in the report template.
So when the report is generated, it will SaveAs another file i.e BSLCT_10072020G.
The code I used to generate is as follow:
Sub Naming reports()
Windows("BSTCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
ActiveWorkbook.SaveAs Path & "\BSLCT_" & REPORT_DATE & "G.xls"
ActiveWorkbook.Close
End Sub
where i define the REPORT_DATE before that.
Now, the users need to have a versioning in their file naming as well, which is something like BSTCT_DDMMYYYYG_vX.xls. So as long as the users run the macro, the macro will generate a new version, regardless of whether the date has already existed.
I managed to create a _v1 using the following codes:
Sub version
Windows("BSTCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name,
InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
ActiveWorkbook.SaveAs (fileName)
Else
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0))
index = index + 1
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name,InStr(ActiveWorkbook.Name, "_v") - 1) & "_v" & index & "." & ext
End If
ActiveWorkbook.SaveAs (fileName)
End Sub
However, after generating the v1, I couldn't generate v1 onwards, because i need to activate the "BSTCT_DDMMYYYYG.xls" window to pick up the report date, this will then break my codes.
Also, while I am adding the version, at the same time i would like to get the DDMMYYYY into the naming too.
How can I do that?
I really appreciate your helps.
now i am trying to keep adding the newer version with the following code:
Sub SaveNewVersion()
Dim fileName As String, index As Long, ext As String, sVersion As String
arr = Split(ActiveWorkbook.Name, ".")
ext = arr(UBound(arr))
sVersion = "_v"
Windows("BSLCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
ActiveWorkbook.SaveAs "\BSLCT_" & REPORT_DATE & "G" & sVersion & index & ".xls"
Else
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0))
index = index + 1
fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, "_v") - 1) & "_v" & index & "." & ext
ActiveWorkbook.SaveAs "\BSLCT_" & REPORT_DATE & "G " & sVersion & index & ".xls"
End If
ActiveWorkbook.Close
End Sub
but at first it keeps replacing my first version, and then saying that this line of code:
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0)) has syntax error.
Does anyone can help on this? I am really clueless where can I modify this.
Try this:
Sub SetNewName()
Dim wbk As Workbook
Dim sDate As String
Dim sVersion As String
sDate = Format(Date, "ddMMyyyy")
sVersion = "_v1"
Set wbk = Application.Workbooks("BSTCT_DDMMYYYYG.xls")
wbk.SaveAs ActiveWorkbook.Path & "\" & sDate & sVersion & ".xls"
End Sub

Using .formula using vba excel

I'm trying link to workbooks. Then Remove the link. The formula is working fine when the Full path is given but fails the moment a string is passed. In the below vba i'm trying to give the name of the location of the files from a cell value in Sheet1.
'Location of Template and Country
Cntryloc = """" & Sheet1.Range("B5") & """"
Debug.Print Cntryloc
TempLoc = "" & Sheet1.Range("B11") & ""
Finaltemplloc = Sheet1.Range("B17")
i=2
'Getting the name of excel Sheet
CntryExcel = Sheet1.Range("C5")
TempLoc = "" & Sheet1.Range("B11") & ""
Workbooks.Open TempLoc & "\" & "Bank" & ".xlsx", True, False
Workbooks("" & FName & ".xlsx").Activate
ActiveWorkbook.Unprotect Password:="Tall.Trees"
Worksheets("Template").Unprotect Password:="Tall.Trees"
Worksheets("Template").Range("D14").Formula = "='&"["&CntryExcel&"]Dump"&"'"&"!"&"$A$" & i""
ActiveWorkbook.BreakLink Name:=Cntryloc, Type:=xlExcelLinks
Worksheets("Template").Protect Password:="Tall.Trees"
ActiveWorkbook.Protect Password:="Tall.Trees"
'Location for Final Output
ActiveWorkbook.SaveAs Filename:=Finaltemplloc & "\" & Bank.xlsx
ActiveWorkbook.Close
try with this
Worksheets("Template").Range("D14").Value = "='[" & CntryExcel & "]Dump'!" & "$A$" & i & ActiveWorkbook.BreakLink & "Name:=" & Cntryloc & ", Type:=" & xlExcelLink
try this
Worksheets("Template").Range("D14").Formula = "='[" & CntryExcel & "]Dump!$A$" & "i"
that should fix the formula input
but check for CntryExcel to hold a workbook name and not a sheet name as per your comment preceeding its initialization ('Getting the name of excel Sheet)

VBA - Trouble with Loop Structure for File Searching and Copying

I'm trying to develop a macro on one of my spreadsheets that will take the value of Column B (2502-13892-33 for example), starting at Row 3, and search the source folder listed in column A for that file (using Wildcards before and after the value in column B. Once it finds that file, it needs to use FileCopy to copy the file into the Destination Folder listed in Column C, but only after renaming the file in the form of "Column E"_"Original Filename (A252_2502-13892-33 for example).
I think I have worked out the code to make this work because when I tested it, it functioned exactly like I expected it to, found the file, copied it to the new destination with the PREFIX from column E and the underscore added to the filename. The problem is that it just stops after the first file, which leads me to believe something is wrong with the structure of my loop.
My code is as follows:
Sub MoveFiles()
Dim SourcePath As String
Dim DestPath As String
Dim PartNum As String
Dim PLISN As String
Dim LastRow As Long
Dim i As Long
Dim filename As String
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To LastRow
PLISN = Cells(i, "E").Value
PartNum = Cells(i, "B").Value
If Right(Cells(i, "A").Value, 1) <> Application.PathSeparator Then
SourcePath = Cells(i, "A").Value & Application.PathSeparator
Else
SourcePath = Cells(i, "A").Value
End If
If Right(Cells(i, "C").Value, 1) <> Application.PathSeparator Then
DestPath = Cells(i, "C").Value & Application.PathSeparator
Else
DestPath = Cells(i, "C").Value
End If
If Dir$(SourcePath & "*" & PartNum & "*") = "" Then
Cells(i, "D").Value = "Source file does not exist."
ElseIf Dir$(DestPath & PLISN & "_" & "*" & PartNum & ".pdf") <> "" Then
Cells(i, "D").Value = "File already exists."
Else
filename = Dir$(SourcePath & "*" & PartNum & "*" & ".pdf")
'Copy the file
FileCopy SourcePath & filename, DestPath & PLISN & "_" & filename
Cells(i, "D").Value = "File Copied to new location"
End If
Next i
End Sub
I had accidentally left my DestinationPath blank for the 2nd and 3rd lines of the excel sheet. That was what was giving me just the "\" as the destination path. Seems to be working properly now.
As someone mentioned below in one of the comments, stepping through my code in the debugger was extremely helpful to solving this problem. My final code has some structural changes, in that I no longer have columns for SourcePath and DestPath, and instead use a folder dialog box to have the user select both of those.
The code for selecting my Source and Destination Folders:
Sub SourceFolder()
Dim lCount As Long
Dim rCount As Long
SourcePath = vbNullString
DestPath = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Title = "Source Path"
.Show
For lCount = 1 To .SelectedItems.Count
SourcePath = .SelectedItems(lCount)
MsgBox (SourcePath)
Next lCount
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Title = "Destination Path"
.Show
For rCount = 1 To .SelectedItems.Count
DestPath = .SelectedItems(rCount)
MsgBox (DestPath)
Next rCount
End With
End Sub
The code for actually going out to the SourcePath, searching for the filename located in Column A (including with wildcards before and after), copying it to the DestinationPath, and renaming it with ColumnB's Value, followed by an underscore, and then ColumnA's Value is as follows:
Option Explicit
Public SourcePath As String
Public DestPath As String
Dim PartNum As String
Dim PLISN As String
Sub MoveFiles()
Dim LastRow As Long
Dim i As Long
Dim filename As String
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To LastRow
PLISN = Cells(i, "B").Value
PartNum = Cells(i, "A").Value
If Right(SourcePath, 1) <> Application.PathSeparator Then
SourcePath = SourcePath & Application.PathSeparator
Else
SourcePath = SourcePath
End If
If Right(DestPath, 1) <> Application.PathSeparator Then
DestPath = DestPath & Application.PathSeparator
Else
DestPath = DestPath
End If
If Dir$(SourcePath & "*" & "*" & PartNum & "*") = "" Then
Cells(i, "C").Value = "Source file does not exist."
ElseIf Dir$(DestPath & PLISN & "_" & "*" & PartNum & "*" & ".pdf") <> "" Then
Cells(i, "C").Value = "File already exists."
Else
filename = Dir$(SourcePath & "*" & PartNum & "*" & ".pdf")
'Copy the file
FileCopy SourcePath & filename, DestPath & PLISN & "_" & filename
Cells(i, "C").Value = "File Copied to new location"
End If
Next i
End Sub

Excel copy from file to file macro not working

I have to copy data from multiple excel files named with numbers (1.xlsx, 2.xlsx, 3.xlsx, etc). I wrote this macro. It runs. But no copy happens, the main workbook in which I ran the macro remains empty.
Sub filecopy()
' The macro is running in the main file, which I saved as .xlsm
' This main.xlsm is in the same folder as the files from which I copy the data
Dim Filename As String, Pathname As String,xx as Double
Activesheet.Usedrange.Clear 'I delete the current contents of the sheet
Pathname = ActiveWorkbook.Path
Filename = Dir(Pathname & "*.xlsx")
xx = 1 'the first column where the contents of the first file goes
Do While Len(Filename) > 0
Cells(1, xx).Formula = "='[" & Filename & "]Sheet1'!A1"
Cells(2, xx).Formula = "='[" & Filename & "]Sheet1'!B2"
Cells(3, xx).Formula = "='[" & Filename & "]Sheet1'!C3"
xx = xx + 1 'next file next column
Filename = Dir()
Loop
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value 'every formula goes to value
MsgBox "Work Complete", vbInformation
End Sub
There are 2 errors in your code:
1. \ is missing -> filename is empty
Replace Filename = Dir(Pathname & "*.xlsx") with Filename = Dir(Pathname & "\*.xlsx")
2. the formula is not correct -> not complete filename
Change your formulas e.g. Cells(1, xx).Formula = "='[" & Filename & "]Sheet1'!A1" with this Cells(1, xx).Formula = "='" & Pathname & "\[" & Filename & "]Sheet1'!A1"
What about a solution like this:
Pathname = ActiveWorkbook.Path 'Be sure is the rigth path
Filename = Dir(Pathname & "\*.xlsx") 'I've addedd a "\"
xx = 1
Do While Len(Filename) > 0
If Filename <> ThisWorkbook.Name Then
Set mFile = Workbooks.Open(Pathname & "\" & Filename)
Else
GoTo NextFile
End If
With mFile.ActiveSheet 'Use the sheet you need here
Cells(1, xx) = .Cells(1, 1).Value
Cells(2, xx) = .Cells(2, 1).Value
Cells(3, xx) = .Cells(3, 1).Value
End With
xx = xx + 1 'next file next column
Application.DisplayAlerts = False
mFile.Close savechanges:=False
Application.DisplayAlerts = True
Set mFile = Nothing
NextFile:
Filename = Dir()
Loop