Search for filename using variable in Excel VBA - excel

I have code that is supposed to search for a filename within a folder on a server and if that file exists the user is prompted to either overwrite the file or not. However, the code always prompts the user regardless of the file existing or not.
I found a few examples off of this site, however they use static file names. I am attempting to modify it to fit my needs, but not getting anywhere.
The code for finding if the file exists is as follows
'checks if file you're saving already exists
If FileThere("\\showdog\service\Service_job_PO\" & UserInput) = True Then
'do stuff here
the function for that code is this:
Function FileThere(filename As String) As Boolean
If FileThere = (Dir("\\showdog\service\Service_job_PO\" & UserInput) <> "") Then
FileThere = True
Else
FileThere = False
End If
End Function

I believe this should be the below. You want to check if the directory associated with the passed parameter filename exists.
Function FileThere(filename As String) As Boolean
If Dir(filename) <> "" Then
FileThere = True
Else
FileThere = False
End If
End Function
Edit:
I'm assuming you feed the full file path in this line, in which case you reference the file path that is sent over to the function FileThere.
If FileThere("\\showdog\service\Service_job_PO\" & UserInput) = True Then

You can cut this all down to a single test rather than double-up with a UDF:
If Len(Dir("\\showdog\service\Service_job_PO\" & UserInput)) > 0 Then
As per other comments above your initial code was using UserInput twice

Related

Check if file exists works in VBA sub but not in VBA function despite calling the same function

I am trying to check for existence of a file
If I run the following code by running a macro
Sub CheckFile()
f = "I:\SomeFolder\a.txt"
returnvalue = Dir(f)
MsgBox (returnvalue)
End Sub
I get "a.txt" in a message box because file exists! As supposed!
But if I write a function
Function FileExists(f)
returnvalue = Dir(f)
FileExists = returnvalue
End Function
and use =FileExists(A1) with A1 having value of "I:\SomeFolder\a.txt"
I get 0 ?????????
Same function, same input, different result. I am lost.
Silly me. I must read upon scope of the variable. Changing (f) to (g) within FileExists definition did the trick.

How to know numerically the last saved file name

I am creating and saving .ini files in Excel. The files need to follow a specific naming convention that increments by 1 each time a file is created. Not all the files will be created in Excel, some will be done in a separate program. Is there a way to read the saved files in their folder to know which number is next?
For example there are files named exampleFile1.ini through exampleFile63.ini. From Excel using VBA or other means can I see that exampleFile63.ini was the last file and name the next exampleFile64.ini?
Thank you. I'm very new if thats not obvious.
This function will return the next available .INI file name:
Private Function GetNextFile() As String
Dim i As Long
Dim fileName As String
For i = 1 To 1000
' Update Path and File Name prefix below to where your .INI files will be stored.
fileName = "d:\path\exampleFile" & i & ".ini"
If Dir(fileName) = "" Then
GetNextFile = fileName
Exit Function
End If
Next
End Function
Call it like this:
Dim NextIniFile As String
NextIniFile = GetNextFile()

VBA script always returns Input past end of file error

I have a csv file as such:
hello,world,this
is,an,example,
of,the,csv,file
The first column will always be unique.
I am getting the user to enter a string which matches an item in the first column, and the script returns the whole line:
Open "C:\file1.csv" For Input As #file_number
Do While (EOF(1) Or found = False)
Line Input #file_number, raw_line
pos = InStr(raw_line, fireName)
If pos = Not 0 Then
strData() = Split(raw_line, ",")
found = True
End If
Loop
Close #file_number
If found = False Then
MsgBox "Could not find it"
Exit Sub
End If
'REST OF THE CODE
But it always sends the message "could not find it" and exits.
By default, found is a boolean value and is false.
I know it can detect the file as when I changed the read file name, it created a new one (as it does not exist).
EDIT:
I changed the And to an Or and now I get the error:
Run-time error 62: input past end of file
It looks like a simple error in your Do While loop. You Check for the EOF instead of not the EOF, as such the loop will never execute since it starts at the BOF.
Something like this should work (my syntax may be slightly off as I haven't used VBA in a while)
Open "C:\file1.csv" For Input As #file_number
While Not EOF(file_number) And found <> False
Line Input #file_number, raw_line
pos = InStr(raw_line, fireName)
If pos <> 0 Then
strData() = Split(raw_line, ",")
found = True
End If
Wend
Close #file_number
If found = False Then
MsgBox "Could not find it"
Exit Sub
End If
The correct way of typing If pos != 0 in VBA is
If pos <> 0
Now it works

How to check whether a input string is a File name or Folder name using Vbscript

My objective is to find whether the given input is s file name or folder name using Vb script.
For example if user gives "D:\Temp\testfile.docx" then it should navigate to File Related Function,
Similarly if user gives "D:\Temp\" then it should navigate to Folder Related Function.
If there is no straightforward solution, Is there any work around to do this ?
Check whether the user input refers to an existing file (.FileExists) or folder (.FolderExists):
If FolderExists(userinp) Then
folderaction
Else
If FileExists(userinp) Then
fileaction
Else
handle bad user input
End If
End If
If that doesn't fit your needs, ask the user to identify folders by always appending "\" and check Right(userinp, 1).
I created this simple function that should suit your needs:
'Return 1 if the provided path is a folder, 2 if it's a file, and -1 if it's neither.
Function GetTypeOfPath(strToTest)
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
If(objFSO.FolderExists(strToTest)) Then
GetTypeOfPath = 1
ElseIf(objFSO.FileExists(strToTest)) Then
GetTypeOfPath = 2
Else 'neither
GetTypeOfPath = -1
End If
End Function
You can test it by creating a file "c:\test" and running `MsgBox(GetTypeOfPath("c:\test"))"; it will return 2. Then delete that file, create a folder "c:\test" and run the same thing; it will return 1. Then delete that and run it a third time; it will return -1.

Determining wrong input file using VBA & Excel

Any suggestions for determining if a user-selected Excel file is the incorrect one? I am having the user select the excel file to be parsed and I want to refuse processing it if appears to be an incorrect format.
If the file being parsed has headings, then check some of the text.
Sub ImportXYZ()
' ... Code to import
If ActiveWorkbook.Worksheets("Sheet1").Range("A1") <> "XYZ" Then
MsgBox CStr(ActiveWorkbook.Name) & vbCr & _
"The file you selected does not contain XYZ data!" & vbCr & "Please try again."
' ... Code to reset
Call ImportXYZ
End If
' ... Code to process import
End Sub
Put a hidden version field or other string in the excel file and break the execution if the string does not match. Assuming of course that you have control over the file or template, from which the file is created.
As an alternative to putting a marker that identifies the right type of file inside a worksheet, you can also use Workbook properties. Create a Custom property "MyExcelFilesClassification", and give the property a value like "MyTypeOfWorkbook". When your code opens the file, check that the Property has the right value, with something like:
Office.DocumentProperties customProperties = workbook.CustomDocumentProperties as Office.DocumentProperties;
foreach (Office.DocumentProperty property in customProperties)
{
if (property.Name == "MyExcelFilesClassification")
{
string modelType = property.Value as string;
if (modelType == "MyTypeOfWorkbook")
{
// do something
}
}
}
This is C# code, but the VBA or VB syntax shouldn't be very different.

Resources