VB.NET Find if file with unknown elements exist? - vb.net

I need to write an if function that finds if the a specific file exists, but the directory of the file contains unknown elements that may change from occasion to occasion. The code I have so far is:
If Dir(ProjectsFolder & ComboBox_ProjectType.Text & "\" & ProjectNumber & "\" & ProjectNumber & "_Rokasgramata\", ProjectNumber & "*User Manual*.pdf")(0) = "" Then
It returns an error and it's probably because of "*" What am I doing wrong? Could someone, please, help me with this one?

When working with paths use IO.Path.Combine
Use that path to create a New IO.DirectoryInfo(path)
This object has .Exists property to ensure that the directory exists.
Finally use .EnumerateFiles(ProjectNumber & "*User Manual*.pdf").Any() To check if any such file exists.

I was very close and figured it out on my own
If Dir(ProjectsFolder & ComboBox_ProjectType.Text & "\" & ProjectNumber & "\" & ProjectNumber & "_Rokasgramata\" & ProjectNumber & "*User Manual*.pdf") = "" Then

Related

Is there a way to Get Last Directory so I can Save As into?

I am able to create a new directory on my desktop, my issues is that I don't know how to save multiple files into that folder, within the same Sub, since it has a dynamic name.
Option Explicit
Sub Make_Folder_On_Desktop()
Dim selectionsheet As Worksheet
Dim Group As Variant
Dim amount As Long
Dim BU As Long
Dim BUname As Variant
Dim sFilename As Variant
Set selectionsheet = Sheets("Project Selection")
Group = selectionsheet.Range("A19").Value
amount = selectionsheet.Range("B19").Value
BU = selectionsheet.Range("B6").Value
BUname = selectionsheet.Range("C6").Value
sFilename = BU & " - " & BUname
MkDir Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - "
& Format(Time, "hhmmss")
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & sFilename
End Sub
Last line is where I'm having the issue. I have "ThisWorkbook.Path" but can't figure out how to get it into the new folder I just created.
MkDir Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - " & Format(Time, "hhmmss")
It's hard to know what the folder name is that you just created, because that instruction is responsible for too many things. Split it up.
Build/concatenate a folder name
Make a directory by that name
If we split up the work, things get much simpler:
Dim path As String
path = Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - " & Format(Time, "hhmmss")
MkDir path
And now we have the path in the ...path variable, readily usable for anything you might want to do with it:
ActiveWorkbook.SaveAs path & "\" & sFilename
As a side note, if you make the date format yyyy-mm-dd instead, you're ISO-compliant (i.e. the date is unambiguous everywhere in the world), and the folders become sortable by name.
Note that the procedure's name is misleading: it doesn't care where the folder is, and there's nothing that says it's under %USERPROFILE%\Desktop. Use Environ$("USERPROFILE") to retrieve the base path for the current user's profile directory.

Copy file and name it a value from the active cell

I need this code to copy the Word file and call it a value from the active cell
FileCopy Application.ThisWorkbook.path & "\template.docx", Application.ThisWorkbook.path & "\exercies\ & Worksheets(1).ActiveCell.Value & "".docx"
But it gives me an error "Bad file of number".
Can someone help me?
The problem is this part of your code:
"\exercies\ & Worksheets(1).ActiveCell.Value & "".docx"
If you Debug.Print this part of the statement, you'll get:
\exercies\ & Worksheets(1).ActiveCell.Value & ".docx
which is not a valid path.
Try replacing it with this instead:
"\exercies\" & ActiveCell.Value & ".docx"
which will produce a valid path. Furthermore, I suspect you have misspelled the folder name. Shouldn't it be exercises instead?

Dir function does not find a file, even after copy pasting the path as a parameter

I've tried to get the Dir() function to work some time now using a rather complicated concatenated string, as seen below:
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
The message box prints nothing (it's just a blank Message Box). After trying to figure out whether I had mistyped the Path somehow, I opened up the correct file, and copypasted its actual Path from options, and subsequently performed: Path = Dir("PathToSubFolder\2016\June\Production June 2016.xlsx"), i.e. without any concatenation or anything, simply just the actual filepath and -name. However, Printing MsgBox Path returned nothing (NULL) again.
Does anyone have any clue as to why this wont work? I have used Dir quite extensively the last days from the same workbook (albeit not from the same module) without any issues.
Edit: Finally found a workaround. I simply made a variable with the path to the file, pathtoFile, and subsequently:
Dim pathtoFile As String
pathtoFile = "C:\Path.to.file\"
Path = Dir(pathtoFile & "*" & MonthName(Month(Date)) & "*")
Month(Date)
Will return a number, not a name. So you are passing the following argument:
PathToSubFolder\2016\6\Production 6 2016.xlsx
Which doesn't exist, hence you get a null string returned.
Try
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
the MonthName() method takes a number between 1 - 12 and returns the name of that month, which is what you need for your string.

Excel-VBA CopyFile Runtime Err 53 (File Note Found)

I am currently having an error with a vba script, tried to fix it but still gives an error as listed in the title.
The aim of the script is to copy file names based on an input form a worksheet and then copy them to a destination saving them with the current date in the name.
Set FSO = CreateObject("scripting.filesystemobject")
FILE = Sheet1.Range("G3").Value
FILE2 = Sheet1.Range("G4").Value
SourceFile = Source & "\" & FILE & ".xls"
DestFile = DestPath & "\" & FILE & " " & ShortDate & ".csv"
SourceFile2 = Source & "\" & FILE2 & ".xls"
DestFile2 = DestPath & "\" & FILE2 & " " & ShortDate & ".csv"
'Setsup Flag File
Dim oFile As Object
Set oFile = FSO.CreateTextFile(DestPath & "\OIS.FLAG")
oFile.WriteLine Format(Sheets("Sheet1").Range("C7").Value, "yyyy/mm/dd")
oFile.Close
FSO.CopyFile SourceFile, DestFile
FSO.CopyFile SourceFile2, DestFile2
Source is just set to "C:\Users\Data"
DestPath is just "C:\Users\updates"
When I run the script the first copy works, so SourceFile is copied, but then the runtime error occurs for the second one SourceFile2, but I've checked multiple times and the SourceFile2 Exists...
Any Tips, or something I'm missing? Also Checked other similar threads, and it's not because the string is too long?
If I input the whole name for SourceFile2 i.e "C:\Users\Data\file2.xls" then it works but I've checked the syntax a million times and seems to be fine, maybe a fresh pair of eyes will help, any suggestions would be massively appreciated :)

Move file into dynamically created folder with VB Script

I am working on a backup script in VBS that creates a folder and then copies a powerpoint file into the most recently created folder.
Everything works great except MoveFile command at the bottom
Here is what I got so far (the bottom code is most important but just so everyone can understand where I am coming from):
sourceDir = "T:\Team"
destinationDir = "T:\Team\Archive\Archive"
const OverwriteExisting = True
intNum = 1
strDirectory = destinationDir & "_" & replace(date,"/",".") & "_" & intNum
'This checks if the folder exists and if not it will create a folder with the date and increment the folder name incase there are multiple updates in a single day.
if not filesys.FolderExists(destinationDir) then
While filesys.FolderExists(destinationDir & "_" & replace(date,"/",".") & "_" & intNum) = True
intNum = intNum + 1
Wend
Set archivefolder = filesys.CreateFolder(destinationDir & "_" & replace(date,"/",".") & "_" & intNum)
Else
Set archivefolder = filesys.CreateFolder(destinationDir)
Set objFolder = fso.CreateFolder(strDirectory)
End if
Dim thisday, thisdayy, thisdayyy
Today_Date()
' This is the problem code
filesys.MoveFile "T:\Arriva\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir & "\" & Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"
Function Today_Date()
thisday=Right(Day(Date),2)
thisdayy=Right("0" & Month(Date),2)
thisdayyy=Right("0" & Year(Date),2)
End Function
This results in a folder being created as "T:\Team\Archive\Archive_03.12.2014_1
My goal is to be able to move the file in T:\Team to the dynamically created folder above.
Everything works great until the MoveFile part. The destination is the part throwing a "type mismatch" at the line where I define the strDirectory
I am just learning this type of programming so please let me know if I can provide any further details!
Thank you in advance!
You have a couple syntax errors with your quotes that are cancelling each other out. Change your line to this:
filesys.MoveFile "T:\Team\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir" & "_" & replace(date,"/",".") & "_" & intNum & "\" & "Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"