VBA checking if file exist using notepad - excel

I would like to ask the community if there is anyway someone can store file directories path into a notepad or other word document and let VBA scan through each file directories and check if file exist.

Here's a commented code that uses dir to illustrate the comment above.
'This function will check if the file or the directory
'exists and returns a boolean.
Function ExistTest(Path As String) As Boolean
'The function default return is set to false
ExistTest = False
'Remove stream reader appending
Path = Replace(Path, "", "")
'Dir returns a 0-length string if the file or directory doesn't exist
If Len(Dir(Path)) > 0 Or Len(Dir(Path, vbDirectory)) > 0 Then
ExistTest = True
End If
End Function
Sub main()
'Defining the source file
Dim SourceFile As String: SourceFile = "d:/t.txt"
'Open a stream reader
Open SourceFile For Input As #1
'Read all line until the end of file
'Before we define a temporary string the path as we go through
'the sourcefile
Dim TempPath As String
Do Until EOF(1)
Line Input #1, TempPath
'Debug print the results
Debug.Print (TempPath & " " & ExistTest(TempPath))
Loop
Close #1
End Sub
Debug.Print will print in the immediate window. To enable that, go to View > Immediate Window

Related

Excel VBA not writing to next text file line

I have the following macro that is should write new data onto a new line in a text/csv file, however it overwriting the existing text in the file, I thought that write wrote to a new line as opposed to print. I am not sure what I am doing wrong
Sub picking()
Range("d14").NumberFormat = "mm/dd/yyyy"
Range("d14").Value = Now
Range("e14").NumberFormat = "hh:mm"
Range("e14").Value = Now
Range("e17").Value = "Picking"
Call outputcsv
End Sub
Sub outputcsv()
Dim Fullpath As String
Dim outputstring As String
Fullpath = Worksheets("Maintence").Range("c5")
Open Fullpath For Output As #1
outputstring = Worksheets("CSV").Range("A1")
Write #1, outputstring
Close #1
End Sub
You just need to change...
Open Fullpath For Output As #1
...to...
Open Fullpath For Append As #1
Note that "Output" changes to "Append."
Also note that "Append" will create the file - just as Output does - if it doesn't already exist. No need to pre-create it.

Excel VBA - Run-time error '53': File not found. But file was found

I have an Excel sheet that pulls data from a folder full of .txt documents.
Last week Friday, it worked. Nothing changed. This week Monday, I get a Run-time error '53': File not found.
What's interesting, is that when I click "Debug" it highlights a line in my code, and when I mouse over the 'sFile' variable, it tells me the name of the file that it apparently can't find... but it could only know the name of it if it found it... And yes, I've verified, that file does exist.
The Excel sheet is in H:\My Documents\Loma CW3 Reports\
The data .txt files are in H:\My Documents\Loma CW3 Reports\Product Statistics\
The first 3 files that it should be pulling are:
- PR20180912T153019.txt
- PR20180913T070005.txt
- PR20180913T153002.txt
Like mentioned above, when I'm debugging the code and mouse-over "sFile" in the line "Open sFile For Input As #1", it tells me:
sFile = "PR20180912T153019.txt"
Which it could only know if it was successfully scanning the folder since I don't hardcode any of those file names in.
I have tried removing that file, renaming the file to a word like 'apple', checked to see if it became read-only (nope). I'm thrown for a loop here, because it worked as is last week, and nothing changed from when I opened it up this week and tried it.
Code below:
Private Sub CommandButton1_Click()
' Dim myFile As String
Dim text As String, textLine As String
Dim sFile As String, rowTarget As Long
rowTarget = 2
' myFile = Application.GetOpenFilename()
sFile = Dir("H:\My Documents\Loma CW3 Reports\Product Statistics\" & "*.txt*")
Do Until sFile = ""
Open sFile For Input As #1
Do Until EOF(1)
Line Input #1, textLine
text = text & textLine
Loop
Close #1
Do stuff here
rowTarget = rowTarget + 1
sFile = Dir()
text = ""
Loop
End Sub
I ended up specifying directory as a separate variable and appended the sFile name to it when opening the file.
Dim directory As String
directory = "H:\My Documents\Loma CW3 Reports\Product Statistics\"
sFile = Dir(directory & "*.txt*")
Do Until sFile = ""
Open (directory & sFile) For Input As #1
blah blah blah
Thanks #comintern

Excel VBA - Check if file exists using Wildcard and open the file

I wish to check whether a file exist in a folder on my computer. I have below, which can see if a specific file exists:
Function FileExists(sFile As String)
sPath = "M:\User\" & sFile & ".xlsm"
FileExists = Dir(sPath) <> ""
End Function
However, my files are named like: Filename - Version xx.xlsm and is updated regularly. Please note that there will only be one file in the folder, but the filename can vary.
How can I search in the folder using wildcard:
Filename - Version % % and then, if it find any file, open the file afterwards?
One option would be to Open the file inside of the FileExists function. However, I would not recommend doing this. The function should do exactly what the name implies and nothing more.
Another option is restructure your code a little bit:
Private Sub OpenFile()
Dim FileName As String
FileName = GetFile("Filename - Version*")
If FileName <> "" Then
'open FileName as needed
End If
End Sub
Private Function GetFile(sFile As String) As String
sPath = "M:\User\" & sFile & ".xlsm"
GetFile = Dir(sPath)
End Function

Ignoring blank lines and spaces in text files when reading

I have a text file with file addresses listed line by line.
Sometimes, however, the users go in there and accidentally add a space or a blank line between the addresses and that crashes the entire code.
How could I avoid this when reading the file using VBA?
This is the current block used to open the text file and read addresses line by line:
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
Set Source = Workbooks.Open(SourceFile)
You will add two lines which will ignore blank lines and spaces like this:
Line Input #1, SourceFile
SourceFile = Trim(SourceFile) '~~> This will trim all the spaces
If Not SourceFile = "" Then '~~> This will check if lines is empty
Set Source = Workbooks.Open(SourceFile)
Suggest you add further code to
test if the file actually exists
test if the file is of a valid type for excel to open
code
Dim SourceFile As String
Dim PathFile As String
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
SourceFile = Trim$(SourceFile)
If Len(Dir(ActiveWorkbook.Path & "\" & SourceFile)) > 0 Then
Select Case Right$(SourceFile, Len(SourceFile) - InStrRev(SourceFile, "."))
Case "xls", "xls*"
Set Source = Workbooks.Open(ActiveWorkbook.Path & "\" & SourceFile)
Case Else
Debug.Print "source not valid"
End Select
End If
Loop
Thanks for the code.
I did some small changes so I can reuse it in many different cases and call at any point of the code, using up to 3 different args (you may increase if you wish). like this below example.
note: you may change "totalBananas,EN2003" to anything you find impossible to exist in your files... I used it this way because I am not sure how to declare the args as optional :-p I don't think they are really possible to be optional anyway.
...
Call FixTextFile(file_name, "blabla", "0000", "")
...
Sub FixTextFile(inFile As Variant, fixArg1 As String, fixArg2 As String, fixArg3 As String)
Dim resArg1, resArg2, resArg3 As Long
Dim outFile As String
Dim data As String
If fixArg1 = "" Then fixArg1 = "totalBananas,EN2003"
If fixArg2 = "" Then fixArg2 = "totalBananas,EN2003"
If fixArg3 = "" Then fixArg3 = "totalBananas,EN2003"
Open inFile For Input As #1
outFile = inFile & ".alt"
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, data
resArg1 = InStr(1, data, fixArg1)
resArg2 = InStr(1, data, fixArg2)
resArg3 = InStr(1, data, fixArg3)
If Trim(data) <> "" And resArg1 < 1 And resArg2 < 1 And resArg3 < 1 Then
Print #2, data
End If
Loop
Close #1
Close #2
Kill inFile
Name outFile As inFile
MsgBox "File alteration completed!"
End Sub

Excel, VBA, Macro, File - Open or Create, Dialog

I am writing a macro in MS excel using VBA. I need to open or create a file to write to.
Potentially the file may have a different extension (i.e. .cal) but internally it just contains text.
I have looked over a lot of examples that create a file by explicitly stating the path for the new file (here's one I found):
strFileName = "C:\test.txt"
Open strFileName For Output As #iFileNumber
Other examples open a file which already exists.
I would like to have a popup/dialog which allows the user to "either" open an existing file "or" create a new one. I assume this is possible.
I have played around with the Application.FileDialog(....) function using strings/paths and objects without much success so far.
With Application.FileDialog(...) your user should be able to create a new text file as they would in Windows Explorer (by right-clicking and selecting New->Text File), they can then select that file to output data to.
The below SelectFile(...) function returns the path to a selected file (or an empty string if no file was selected). Using this function as-is it is only possible for the user to select one file, but given the context I would hope this isn't a problem.
Public Sub SelectOrCreateFile()
Dim strFileName As String
Dim iFileNum As Integer
iFileNum = FreeFile
strFileName = SelectFile
If strFileName <> "" Then
Open strFileName For Output As #iFileNum
'### WRITE YOUR DATA ###
Close #iFileNum
End If
End Sub
'Returns File Path of file selected with file selection dialog
Public Function SelectFile(Optional DefaultPath As String = "", _
Optional FileType As String = "All Files", _
Optional FileExtension As String = "*.*") As String
Dim F As Object
Set F = Application.FileDialog(msoFileDialogFilePicker)
'Set up FileDialog properties
F.Filters.Clear
F.Filters.Add FileType, FileExtension
F.AllowMultiSelect = False
F.Title = "Select File"
F.ButtonName = "Select"
If DefaultPath <> "" Then F.InitialFileName = DefaultPath
'FileDialog.Show returns False if the user cancels
If F.show Then
SelectFile = F.SelectedItems(1)
Else
MsgBox "No File Selected", vbInformation, "Cancelled"
SelectFile = ""
End If
Set F = Nothing
End Function
Hope this helps!

Resources