VB Script to update existing number in existing text file [closed] - file-io

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm sure this is simple but my programming skills are next to none.
I have a text file that contains a number and always a number, e.g. 1. I need a VBScript to always add 1 to that number in that text file, update, save, then close. The new file should contain 2.
The next time I execute the script, the file should contain 3 and so on.

Here's what I scraped together, assuming you meant VBScript and not VB.NET:
Option Explicit
Dim filename
filename = "C:\Path\To\Your\file.txt"
Dim fso, f, num
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, 1) ' for reading
num = CInt(f.ReadAll)
f.Close
Set f = fso.OpenTextFile(filename, 2) ' for writing
f.Write num + 1
f.Close
Keep in mind that there is no error handling in that code.

Related

VBA - Loop through multiple subfolders on a network location with date search criteria/ Improve search speed

Purpose of my question and of the VBA code:
Get specific data (a couple columns) from each one of the "table.csv" file in a network directory. Each networkdirectory/subfolders01/subfolders02 contains one "table.csv" file but 100 other subfolders are included in each network/subfolders01. The other folders are not needed, the only one we are interested in is subfolder02 for each subfolder01. The number of subfolders01 in the network directory is about 15000. However I only need subfolders01 from Jan2020 to Apr2020,for example (200 subfolders).
Final purpose is to trend data.
Issue:
I am trying to understand how I could improve the VBA code that I am currently using.
This code goes through each subfolder one by one and then check the date and file name.
I am wondering if there is a way to add any search filters criteria for subfolder date and name to have a faster loop.
How can we avoid the code to go through each subfolders?
Please see below the code I am using,
I really appreciate your time and hope my request is clear.
'''
Function GetFiles(startPath As String) As Collection
Dim fso As Object, rv As New Collection, colFolders As New Collection, fpath As String
Dim subFolder As Object, f, dMinfold, dtMod
Set fso = CreateObject("Scripting.FileSystemObject")
dMinfold = ThisWorkbook.Sheets("Enter_Date").Cells(2, 1)
colFolders.Add startPath
Do While colFolders.Count > 0
fpath = colFolders(1)
colFolders.Remove 1
'process subfolders
For Each subFolder In fso.getfolder(fpath).subfolders
If subFolder.DateLastModified >= dMinfold Then
colFolders.Add subFolder.Path
End If
Next subFolder
'process files
f = Dir(fso.buildpath(fpath, "*Table.csv"), vbNormal)
Do While f <> ""
f = fso.buildpath(fpath, f)
dtMod = FileDateTime(f)
If dtMod >= dMinfold And Right(f, 3) = "csv" Then
rv.Add f
End If
f = Dir()
Loop
Loop
Set GetFiles = rv
End Function'''
Then I have my code to get transfer data from each file.
Thank you.
I'll put in screenshots to clear up the Get & Transform method, since it is the GUI approach rather than code.
It is possible to filter before loading contents, which will speed things up significantly.
I tried with a few thousand subfolders filtered down to 20, loads instantly.
Here's the initial screen for get data from folder
You can then filter on path. In your case it will be based on the date from the folder name.
Now that it's filtered you can expand the content using the header button.
Inside content, you'll have to expand again to convert from csv to excel table
Choose/rename columns as needed, then hit "close and load" to drop it into excel.
Default is to a new table, but you can "load to" if something more custom is needed.
Here's your output. You can right-click refresh or refresh from vba as needed.
Edit- Just noticed that I used .txt rather than .csv for the files. Might change how a step or two looks in the middle, but the general idea is the same.

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

Excel VBA code that searches multiple documents for a text [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 am looking for help, I have a very basic knowledge of VBA and can't perform complex tasks, would someone be able to provide the base of the code and I'll be able to study it and expand on it?
The code should be able to perform the following task:
Using a list of document names in excel, open those documents (word documents) and search the first page for a specific text. If the text exists return TRUE, else FALSE.
Please note the documents are all stored in sub folders.
Thank you,
There are tree different question you have to ask yourself before posting:
I will try to answer it in the way you asked:
1 - Read documents name from the excel file
Dim fileNames as new Collection
For Each name in Range("names")
fileNames.Add name
Next name
2 - Open Word documents
Add the Microsoft Word 12.0 Object Library to your references, and use the Word API to open and read the document.
Dim doc As Word.Document
Set doc = Word.Documents.Open(Filename:=DocumentPath, Visible:=False)
3 - Find text in the active document
Dim myRng as Word.Range
Set myRng = doc.Content
then use the find object for your purpose, take a look at the documentation
https://msdn.microsoft.com/en-us/vba/word-vba/articles/find-object-word

Is there a way to save all hyperlinked documents in excel?

I know this question has been answered before, but the problem I'm facing is a bit different, and this is why I'm asking for your help :)
So, I'm working with multiple excel files that contain multiple hyperlinks that lead to documents such as Excel files, PDFs, DOCs and sometimes even images. The problem with these hyperlinks is that they are not leading to a "normal" website, but to a special internal software, that in its turn links to a local address on my computer that contatins the desired file. That means that there is no direct link that could be grabbed with a simple VBA code.
Let's have an example, assuming the internal software name is "John":
I see in the Excel documents this link: John://3434545345/345345345
When I click on it, it opens the file, which is located, for example, in: C:/local/Cutekitten.pdf
After this long intro, my question is: Is there a way to automate the process of saving each document, instead of manually opening it and saving it? Could it be solved with a VBA code? Or does is require a different approach? I was actually thinking to bypass this problem by finding a way to open all hyperlinks at once with VBA, and then maybe find some code (not VBA?) that saves all open documents.
P.S Please keep in mind that I can't download EXE files or any other "suspicious" files due to workplace restrictions.
Any help will be much appreciated,
Thanks! :)
You may try this
'''
Input: test.xlsx
name link
1 location/file1.jpg
2 location/file2.xlsx
3 location/file3.pdf
4 location/file4.mp4
'''
from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
print wb.get_sheet_names()
# ['Sheet 1', 'Sheet 2', 'Sheet 3']
ws1 = wb['Sheet 1']
## alternate -> worksheet2 = wb2.get_sheet_by_name('Sheet2')
import urllib
import os
## Result directory
directory = 'result'
if not os.path.exists(directory):
os.makedirs(directory)
for row in ws1:
if '.exe' in row[1].value:
continue
print row[0].value, '\t', row[1].value
urllib.urlretrieve (row[1].value, directory+'/'+row[1].value)
'''
Output:
Table 1 None
None None
name link
1 location/file1.jpg
2 location/file2.xlsx
3 location/file3.pdf
4 location/file4.mp4
'''
Sub PathsText()
Dim List(), Path As String
Dim i, x As Integer
Dim s As InlineShape
Dim fso As FileSystemObject, ts As TextStream
Set fso = New FileSystemObject
Set ts = fso.OpenTextFile("C:\MyFolder\List.txt", 8, True)
With ts
.WriteLine (ActiveDocument.InlineShapes.Count)
End With
For Each s In ActiveDocument.InlineShapes
Path = s.LinkFormat.SourcePath & "\" _
& s.LinkFormat.SourceName
With ts
.WriteLine (Path)
End With
Next s
End Sub
I guess the important part is if "Path = s.LinkFormat.SourcePath" works.
If so, if you have a ton of excel files to do it for, I'd put those (the ones with the links) in one folder. I'd make a new empty workbook with one button on a single sheet to call code. The button would "For Each workbook in directory, For Each sheet in workbook, For Each link on sheet" add source path to a text file.
Once you had a list of paths the next step would be obvious. I wish I had demo code, but I migrated to c# years ago. My monstrously slow cell-by-cell search, modify and graph inventions threatened to bury me.

Snapshot of data structures, VBA excel [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
What's the fastest way to export all excel add-in modules to .bas files?
Is it possible to do snapshot of all used modules and data structures in VBA Excel and recover it some time after?
The reason is reproducing error after crashes
ADDED. Yes, in essence I want to serialize classes and types.
I feel like what you kind of want is to serialize all your classes as
they are to an XML file? I know this function exists in other
languages but VBA might not have it as it is. (I'm sure you could
force something) – Brad
#Brad, yes, exactly, as one of possible ways – nikaan
Assuming that this method does not exist for VBA (although it is available for VB.NET or VB 2005: http://support.microsoft.com/kb/315703), I would probably try to make a simulation: Write the state of each object / variable (of those needed) to a txt file by using FSO.
I don't know if this is feasible for your project though and I probably wouldn't like to do this with pleasure for a huge amount of code.
dim sFile As string
Dim FSO As FileSystemObject
Dim FSOFile As TextStream
sFile = "U:/Log.txt"
Set FSO = New FileSystemObject
Set FSOFile = FSO.OpenTextFile(sFile, 2, True)
FSOFile.writeline (<Descriptions+Property/variable value>)
FSOFile.Close
set FSO = nothing
Depending on how well you input descriptions (eg. inlcuding boolean values for successful instantiation of objects, etc...), you may be able to see what has happened behind the screen up to the point where your application crashed...
I don't know if this answers your question, as I'm a little bit doubting about what you refer to with "fields" (comments).
When being the owner of a VBA project, you can create a sub routine that exports all the modules in your currenct project.
This link provides the code:
http://edndoc.esri.com/arcobjects/9.0/Samples/Application_Framework/ExportVBACode.htm
For the purpose as you describe it, I don't see a reason to do this.
Personally I would use a lame trick like this one:
Option Explicit
Sub Save_File()
Dim sCur_Path As String
Dim sCopied_Path As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
sCur_Path = ThisWorkbook.FullName
sCopied_Path = "U:/Copied_New.xlsm"
ThisWorkbook.SaveAs sCopied_Path
ThisWorkbook.SaveAs sCur_Path
End Sub