VBA Conditional Save As with Date Add [closed] - vba

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am using Excel 2010 and am trying to use a macro for the following:
Open the Save As dialogue box
Take the initial file name and check IF there is an underscore followed by 8 consecutive integers (ie. _12345678) before the file type (ie. .xlsx)
IF that DOES EXIST remove and replace it with an underscore followed by today's date in "yyyymmdd" format (ie. _20130730) before the file type (ie. .xlsx)
IF that DOES NOT EXIST simply add an underscore followed by today's date in "yyyymmdd" format (ie. _20130730) before the file type (ie. .xlsx)
The new file name based on criteria above would be present in the File Name field in the open Save As dialogue box but the file will require user to actually save it (just naming and opening Save As. Not actually saving with VBA)
Maintain whatever the original file type is
Assuming today's date is 7/30/2013, the macro would work as follows for the following beginning files:
1.) Test File A_20130615.xlsx would become Test File A_20130730.xlsx
2.) Test File B.xlsx would become Test File B_20130730.xlsx
Any and all help is appreciated!
Thanks

I modified a routine I have that does the same type of thing that you are trying to do, but uses the current name of the file, instead of having 2 save dialog boxes.
Option Explicit
Function SaveIt()
Dim CurrentFile As String
Dim FileExt As String
Dim GetFileName
CurrentFile = Left(ActiveWorkbook.FullName, InStrRev(ActiveWorkbook.FullName, ".") - 1)
FileExt = Mid(ActiveWorkbook.FullName, InStrRev(ActiveWorkbook.FullName, "."))
If InStr(CurrentFile, "_") Then
'has underscore
If InStrRev(CurrentFile, "_") = Len(CurrentFile) - 8 Then
' underscore 8 from end
If Right(CurrentFile, 8) = CStr(Val(Right(CurrentFile, 8))) Then
' and it's 8 digits at the end
CurrentFile = Left(CurrentFile, Len(CurrentFile) - 9)
'strip the end off
End If ' if it fails any of these tests,
End If 'then it's not got the underscore and date
End If ' and we don't touch the filename
CurrentFile = CurrentFile & "_" & Format(Now, "yyyymmdd")
GetFileName = Application.GetSaveAsFilename(CurrentFile & FileExt)
If GetFileName <> False Then 'Cancel returns false, otherwise it returns the filename
ActiveWorkbook.SaveAs GetFileName
End If
End Function
This also allows for people to have files named test_1.xlsx and What_a_lot_of_underscores.xlsm without having to worry about something destructing the name

Related

vb exporting the contents of a textbox into a txt file on the PC with different names for each file automatically

I have found the following code on another website - a print function that exports the code in the textbox into a txt file in the c drive of my PC.
When trying to alter it to make it suit my code it, doesn't work and I was wondering what's wrong with what I've got?
The code is as follows ..
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
I then changed the "here is the first string." to the contents of the textbox (which is also a list) and also changed the location of the file to make it able to make a new file every time based on the date and time of the PC running it like as follows.
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\" + OrderType.txtCustPhoneNumber.Text + " " + Today + " " + TimeOfDay, True)
file.WriteLine(txtBoxOrder.Text)
file.Close()
The variables of Today and TimeOfDay being the date and time according to the system and the textbox "OrderType.txtCustPhoneNumber.Text" being a textbox that individualises different files if the times and dates clash.
This is because the software will be run on two PCs that share the same storage.
Try this:
Dim filename as String
filename = "C:\" & OrderType.txtCustPhoneNumber.Text & "_" & Now.ToString("MMddyyyy_hhmmss")
file = My.Computer.FileSystem.OpenTextFileWriter(filename, True)
You can apply a format to the timestamp. My personal preference is to build filenames into strings and to not use spaces. YMMV.

VBA - Reading PDF as String - Cannot sometimes but can other times - 'Run time error 62' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
You can open PDFs in text editors to see the structure of how the PDF is written.
Using VBA I have opened a PDF as a text file and go to extract the text and save it as a string variable in VBA. I want to look through this text to find a specific element; a polyline (called sTreamTrain) and get the vertices of the polyline by using the InStr function.
When i add more vertices to the polyline I cannot seem to extract the text string of the pdf. I get the error 'Run time error 62' which I do not understand what it means or what about the PDF has changed to now have this error.
Attached (via the link) is a PDF that I can read (Document 15) and a PDF I cannot read (Document 16). I have checked in excel so see that the vertices are present in both files. Also there is a copy of my VBA script as a notepad document and also my excel file (but it is difficult to find in my excel file - the script is "Module 6" function called "CoordExtractor_TestBuild01()")
Link:
https://drive.google.com/open?id=1zOhwnFWZZfy9bTAxKiQFSl7qiQLlYIJV
Code snippet of the text extraction process below to reproduce the problem (given an applicable pdf is used):
Sub CoordExtractor_TestBuild01()
'Opening the PDF and getting the coordinates
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\Users\KAllan\Documents\WorkingInformation\sTreamTrain\Document16 - Original.pdf"
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
Dim Temp As Long
Temp = LOF(TextFile)
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
End Sub
I would like someone to let me know what runtime error 62 is in this context and propose any workflows to get around it in future. Also, I would like to know whether there certain characters you cannot store as strings? - Perhaps these are included when I increase the number of vertices past a certain number.
Also I would prefer to keep the scrips quite simple and not use external libraries because I want to share the script when it is done so others can use it thus its simpler if it works without extra dependencies etc, however, any and all advice welcome since this is only the first half of this project.
Thank you very much.
According to the MSDN documentation, this error is caused by the file containing
...blank spaces or extra returns at the end of the file or the syntax
is not correct.
Since your code works sometimes on documents with very similar names and content to documents where it doesn't work, we can rule out syntax errors in this case.
You can clean up the file contents before processing it any further by replacing the code at the top of your macro with the one below. With this I can read and extract information from your Document16.pdf:
Sub CoordExtractor_TestBuild01()
'Purpose to link together the extracting real PDF information and outputting the results onto a spreadsheet
'########################################################################################
'Opening the PDF and getting the coordinates
Dim n As Long
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\TEST\Document16.pdf" ' change path
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
Dim strTextLine As String
Dim vItem As Variant
Line Input #1, strTextLine
vItem = Split(strTextLine, Chr(10))
' clean file of garbage information line by line
For n = LBound(vItem) To UBound(vItem)
' insert appropriate conditions here - in this case if the string "<<" is present
If InStr(1, vItem(n), "<<") > 0 Then
If FileContent = vbNullString Then
FileContent = vItem(n)
Else
FileContent = FileContent & Chr(10) & vItem(n)
End If
End If
Next n
'Clost Text File
Close TextFile
' insert the rest of the code here

Can VBA open the newest spreadsheet by reading its name? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I receive a weekly Excel file from my IT department with an updated list of employees, their supervisor, department, etc. Every week, I just drag the file from the email into a designated folder on my computer.
Occasionally, I'll want a VBA script to reference and copy info from the latest version of whatever listing IT has sent to me most recently. The naming convention for the file is always the same: "EmployeeListing_20171211," but obviously with the date in the name being whatever day the file is generated. So next week, I can expect the new file to be named "EmployeeListing_20171218."
Because these files are stored in a shared folder, I have no way of knowing if other people are opening & modifying them, so I don't want the script to go by most recent Date Modified, but instead be able to read the date from the name of the file and select the file that's the newest. And all the questions I've seen related to this seem to point towards opening the file that has the most recent Date Modified, not in whose name includes the most recent date.
To do this, it seems to me like I need to read in the names of all the files in the folder, tell VBA how to convert the string to a date, find the date that's the most recent, and then find the corresponding Excel file that matches this date. But I have no idea where to start. Can anyone help with this?
Here's some code with comments that will get you started.
Sub test()
Dim sFile As String
Dim sPath As String
Dim dtFile As Date
Dim dtMax As Date, sMax As String
Dim sDate As String
'Folder where your files live
sPath = Environ("userprofile") & "\Documents\MyFolder\"
'Get the first file that starts with EmployeeListing_
sFile = Dir(sPath & "EmployeeListing_*")
'If there are no files, the lenght = 0
Do While Len(sFile) > 0
sDate = Split(sFile, "_")(1) 'get the date part of the file name
'turn it into an actual date
dtFile = DateSerial(Left$(sDate, 4), Mid$(sDate, 5, 2), Mid(sDate, 7, 2))
'if it's bigger than any others, store the date and name
If dtFile > dtMax Then
dtMax = dtFile
sMax = sFile
End If
'no arguments means get the next file using the same arguments as
'previosly supplied
sFile = Dir
Loop
'Print the file with the biggest date
Debug.Print sPath & sMax
End Sub

VB.net String Extraction

At the company I work at, I have a software that I am developing in vb.net. This software uses a web browser control to load an excel file that the employee can modify. If then saves a copy of the excel file as an excel file for future modification, it saves it as a pdf file, to send to the customer, then prints the first page twice. I am trying to create a quote list. Quote File names are structured as follows...
12345 My Company Name Here 10-25-2013.pdf
Is there any way to "extract" just the "My Company Name Here" in the above example. I tried removing all numbers, and then the - and .pdf from the string, but it actually makes it where fewer results appear in the list view control. Any Ideas?
Dim di As New IO.DirectoryInfo("Z:\Quotes\" & Today.Year & "\" & Today.Month _
& " " & MonthName(Today.Month))
Dim diar1 As IO.FileInfo() = di.GetFiles("*.pdf")
Dim dra As IO.FileInfo
ListView1.View = View.Details
ListView1.Columns.Clear()
ListView1.Columns.Add("Quote Number")
ListView1.Columns.Add("Customer Name")
ListView1.Columns(0).Width = -2
ListView1.Columns(1).Width = -2
For Each dra In diar1
If dra.ToString.Contains("Product") = False Or dra.ToString.Contains("Thumbs.db") Then
Dim newIrm() = dra.ToString.Split(" ")
Dim NumericCharacters As New System.Text.RegularExpressions.Regex("\d")
Dim nonNumericOnlyString As String = NumericCharacters.Replace(newIrm(2), String.Empty)
ListView1.Items.Add(New ListViewItem({newIrm(0), newIrm(1) & newIrm(2)}))
End If
Next
Filename Format:
Z:\Quotes\2013\10 October\12345-RR My Company Name Here 10-25-2013.pdf
By assuming that the company name is always surrounded by blank spaces and that all the surrounding text does not contain any, you can use IndexOf and LastIndexOf. Sample code:
Dim input As String = "Z:\Quotes\2013\10 October\12345-RR My Company Name Here 10-25-2013.pdf"
Dim companyName As String = System.IO.Path.GetFileNameWithoutExtension(input)
companyName = companyName.Substring(companyName.IndexOf(" "), companyName.LastIndexOf(" ") - companyName.IndexOf(" ")).Trim()
If these conditions do not fully apply, you would have to describe clearly the constraints in order to update this code. Without systematically-applied constraints, there wouldn't be any way to deliver an accurate solution for this problem.
The postfix (date.pdf) is a constant size assuming your date format uses leading zeros.
The prefix is a variable size, however the first space of the complete file name always comes before the first character of the company name.
Using these two facts, you can easily find the index of the first and last character of the company "extract" the company name using this information.
Alternatively, you can split the file name into an array using space as your delimiter. You can then grab every index of the array, excluding the first and last index, and combine these elements seperated by a space.

FORMTEXT Appearing in Word File Name Generated from Protected Form-Field Value and BookMark for VB Script

I am using the following VB Script in a Word 2010 Doc saved as a Microsoft Word Macro-Enabled Template that is protected for form fields:
Sub SaveWithBkMarkedText()
'This code saves the Word file using the bookmark value for Maintenance Memo.
'The file is also saved to a folder in KnowHow for files related to this template.
Dim FileName As String
FileName = ActiveDocument.Bookmarks("mmn").Range.Text
'Use the C:\ code when saving the file locally
ActiveDocument.SaveAs "C:\Download\TemplatesFolders\" & FileName & ".doc"
MsgBox "Your Draft has been saved to KnowHow's Release Documentation site." & _
&vbCrLf & "The file name uses the MM that you included earlier: " & FileName, _
vbInformation + vbOKOnly, "Draft Saved to Minerva"
End Sub
The value entered into the Form Field for a FORMTEXT legacy-form object uses the Bookmark as the file name. Example, if the user enters 12345 as the value, the file is saved using this value as the filename: 12345.doc. This worked fine until a week ago when the filename is now being Prefixed with FORMTEXT 12345.doc. I have tried using this same VB script in older versions of Word on a different machine, and created from a NEW Template with the script added in from scratch, and the same issue is appearing on that machine as well. Prior to this, I was able to update my template with NO problem, but now I can't update this one FORMTEXT field without it affecting the whole file. I can update any other FORMTEXT in the template that does not use the Bookmark value as the file name, and it works. Also, I have tried changing the Bookmark Reference to another FORMTEXT object, as well as saving the file as a .DOCX and the same problem occurs regardless. What is causing the FORMTEXT to appear in the filename?
You have to un-protect the document (template) and then make the VBA programming. Once it is done, then you can protect it again (for filling forms) and you will not see the "FORMTEXT" in the filename when you run the macro.
Hope it helps.
To the OP, did you resolve this issue? I'm now having the same problem, I'm using form field text with bookmarks and using VB.net to get the bookmark.text which is now prefixed with FORMTEXT, just using a bookmark on it own and its OK, no prefix. I'm going to try and remove the first 9 characters from the result using code, a workaround, yes but it might work.
Know this is an old thread but ran into same issue. As a workaround...
Replace FORMTEXT with null "". In OP circumstance:
Dim FileName As String
FileName = ActiveDocument.Bookmarks("mmn").Range.Text
FileName = Replace(FileName, "FORMTEXT ", "")
Not a "fix" for the issue or elegant but it works.
Had the same issue. Simply delete current bookmark and add a new one. If that does not work than instead of using the following:
FileName = ActiveDocument.Bookmarks("mmn").Range.Text
try using:
Selection.GoTo What:=wdGoToBookmark, Name:="mmn"
Filename = Selection.Text