I am trying to make a simple counter that adds one to the count every time the script is run. I have tried using a property but that doesn't work because it resets whenever the script is edited or the computer is turned off. Here is the code I have that I took from here.
set theFile to ":Users:hardware:Library:Scripts:Applications:LightSpeed:" & "CurrentProductCode.txt"
open for access theFile
set fileContents to read theFile
close access theFile
set counter to fileContents as integer
on add_leading_zeros(counter, max_leading_zeros)
set the threshold_number to (10 ^ max_leading_zeros) as integer
if counter is less than the threshold_number then
set the leading_zeros to ""
set the digit_count to the length of ((counter div 1) as string)
set the character_count to (max_leading_zeros + 1) - digit_count
repeat character_count times
set the leading_zeros to (the leading_zeros & "0") as string
end repeat
return (leading_zeros & (counter as text)) as string
else
return counter as text
end if
end add_leading_zeros
add_leading_zeros(counter, 6)
open for access newFile with write permission
set eof of newFile to 0
write counter + 1 to newFile
close access newFile
With this I get the error:
Can’t make ":Users:hardware:Library:Scripts:Applications:LightSpeed:CurrentProductCode.txt" into type file.
If I add "set theFile to theFile as alias" after the first "open for access theFile" it gets a little further in the code, but gets another error:
Can’t make "1776" into type integer.
And now I am out of ideas. I have googled all over the place haven't found anything that works for me. Thanks
I like to use script objects to store data:
set thePath to (path to desktop as text) & "myData.scpt"
script theData
property Counter : missing value
end script
try
set theData to load script file thePath
on error
-- On first run, set the initial value of the variable
set theData's Counter to 0
end try
--Increment the variable by 1
set theData's Counter to (theData's Counter) + 1
-- save your changes
store script theData in file thePath replacing yes
return theData's Counter
Related
I have a code, in which I want to loop through files in a folder, check their built-in or custom document properties (without opening them), and later open those, which are meant to be open.
To do this, I'm using Shell and to set the folder I'm using Shell.Namespace.
The problem is with the Namespace, I guess. When I use a variable strSuborCesta for the path it doesn't work. When I print the variable strSuborCesta into immediate window and use the printed string inside the Shell.Namespace("....") it does work.
By it doesn't work I mean I get:
run-time error : 91 Object variable or With block not set
when I try to loop through the files in folder (which is not set in that case, so I understand why the error occurred, but don't understand why it's not accepting a string variable)
The path is correct in both ways. But I need it to be a variable, not a hardcoded string.
Where do I error?
Is there any better way, to check document properties (like comments, title, author, etc.) without opening the Excel files?
Below is the section (currently just in testing phase) that is giving me a hard time.
str[name of variable] variables are string data types. sFile, oShell, oDir are as Variants
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get a root path
strPriecinokCesta = ThisWorkbook.Path 'path to this file
strPriecinokCesta = Left(strPriecinokCesta, Len(strPriecinokCesta) - (Len(strPriecinokCesta) - InStrRev(strPriecinokCesta, "\"))) 'root path is one level above this file
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'input files are in a subfolder
strSuborCesta = strPriecinokCesta & "Zdroje\"
strSuborPripona = "Formular_BD_kotolna*.xls" 'name of a file with extension
strSuborNazov = Dir(strSuborCesta & strSuborPripona) 'actual file name
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get access to the file system
Set oShell = CreateObject("Shell.Application")
Set oDir = oShell.Namespace(strSuborCesta) '<----this will produce an error. In contrast to using a hard coded string. Why?
For Each sFile In oDir.Items '<---- run time error 91 occurs on this line
Debug.Print test & " : " & oDir.GetDetailsOf(sFile, 24) 'comments
Next
Variable strSuborNazov should be a variant
Dim strSuborNazov as variant
oShell.Namespace(strSuborNazov)
https://msdn.microsoft.com/en-us/library/windows/desktop/bb774085(v=vs.85).aspx
Here's a script that renames a group of files to their new filenames created in excel. It works and it's great! But the problem is if the files do not exist from the group of files the scripts ends and creates an error..
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
set {oldDelims, text item delimiters} to {text item delimiters, tab}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
I asked around for some help and they gave me this code to add. The problem is I do not know how and where to add this code and how to define it. I want to be able to create a .txt file that contain the files not renamed instead of stopping the whole script.
try
set name of file codified_name to real_name
on error error_string number error_number
write error_string to log_file_handle starting at eof
end
I don't really know how to code and just rely on posts from the internet and try to tweak them. So if anyone can help me..that would be really really awesome!
Here, this shows how to add a try block into your code above. You needed more code to write to an error log file as well. Should be enough to go on:
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set log_file_path to "Macintosh HD:Users:COMP1:Desktop:myErrorLogFile.txt"
set {oldDelims, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tab}
try
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
set AppleScript's text item delimiters to oldDelims
on error error_string number error_number
set AppleScript's text item delimiters to oldDelims
set log_file_handle to (open for access file log_file_path with write permission)
write ((current date) as string) & tab & error_string to log_file_handle starting at eof
close access log_file_handle
end try
Now, I am writing a VBA program. In my program, firstly I need to count all line from a file. I need line count because of creating array for line in file. So, I used this code. It is OK.
'Open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read all line
file.ReadAll
'Get line count
lineCount = file.line
'Close file
file.Close
After getting line count, I want to subtract 2 from it for header and footer(the blank line). I don't know which word will be header. I only know row that they are first row and last row(the blank row).
'Remove header and blank line from line count
lineCount = lineCount - 2
And then, I wanna read that file line by line which are only useful for me and store all line in array. The problem is at that, when reading line by line, It is need to re-open file. Only after re-open, I can read line by line.
Because, "ReadAll" method is readed all line and the index of file object is shown "AtEndOfFile". So, I must re-open it. Please check my code.
'If line count is greater than 0, read again file to get data
If lineCount > 0 Then
'Re-define array size
ReDim lineList(lineCount) As String
'Here I opend it, I don't wanna open. I just want to set index of file object.
'Re-open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read file until end
Do Until file.AtEndOfStream
'If current line is not first line(header) or last line(blank line)
If line <> 0 And line <= lineCount Then
'Store line into array
lineList(index) = file.ReadLine
'Increase array index
index = index + 1
Else
file.ReadLine
End If
'Increase line index
line = line + 1
Loop
End If
But, I want another way. I don't wanna re-open file. I want to reset the index to the first line of file object. So, I don't need to re-open it.
I already search about it in internet. But, I didn't found any suggestions for that. Please help me. Thanks.
My approach is slightly different than your current approach, I would use the Binary read to read the file and save it in a temporary string, then use Split function to put them in an Array.
This method has one drawback as in the if the length (number of characters) of the file is greater than the size of a String variable then we might have issues but other than that. This is quite different approach.
Public Sub ReadFileData(filePath As String, Optional separatorStr As String = ";#;")
'******************************************************************************
' Opens a large TXT File, reads the data until EOF on the Source,
' then stores them in an Array
' Arguments:
' ``````````
' 1. The Source File Path - "C:\Users\SO\FileName.Txt" (or) D:\Data.txt
' 2. (Optional) Separator - The separator, you wish to use. Defauls to ';#;'
'*******************************************************************************
Dim strIn As String, tmpStr As String, lineCtr As Long
Dim tmpArr() As String
Open filePath For Input As #1
Do While Not EOF(1)
'Read one line at a time.
Line Input #1, strIn
tmpStr = tmpStr & Trim(strIn) & separatorStr
lineCtr = lineCtr + 1
Loop
Close #1
tmpArr = Split(tmpStr, separatorStr)
Debug.Print "Number of Elements in the Arrays is - " & UBound(tmpArr)
Debug.Print "Number of Lines Read is - " & lineCtr
End Sub
I have a number written in a text file. Is it possible to add another to the number in the text file then replace the old number with the new one? Heres my code:
set theFile to POSIX path of "Users:Tyler:Documents:File.txt"
open for access theFile
set theFileContents to read theFile
set theNewFile to run script theFileContents + 1
tell application "TextEdit"
set eof of theFileContents to 0
write theNewFile to theFileContents
if i understand your question correctly you just want to have a text file with a string and convert that string to a number then increase the value of the number by 1 write it back to the file as a string and save it boom done right ? let me know if this is what you meant.
set docsFolder to path to documents folder
set afile to "" & docsFolder & "File.txt"
open for access file afile with write permission
set oldNum to read file afile
set newString to ((oldNum as number) + 1) as string
set eof file afile to 0
log newString
write newString to file afile starting at eof
close access file afile
This is a simple VBS script. But when I double-click on this, I get Invalid Character 800A0408 on Line 1, Character 1, which I think is the first "Dim". I am new to VBS--can u tell me what I did wrong? FYI, I have an XP OS and IIS6 Manager installed.
' This script adds the necessary Windows Presentation Foundation MIME types
' to an IIS Server.
' To use this script, just double-click or execute it from a command line.
' Running this script multiple times results in multiple entries in the IIS MimeMap.
Dim MimeMapObj
Dim MimeMapArray
Dim WshShell
Dim oExec
Const ADS_PROPERTY_UPDATE = 2
' Set the MIME types to be added
Dim MimeTypesToAddArray = Array(".manifest", "application/manifest", ".xaml", _
"application/xaml+xml", ".application", "application/x-ms-application", _
".deploy", "application/octet-stream", ".xbap", "application/x-ms-xbap", _
".xps", "application/vnd.ms-xpsdocument")
' Get the mimemap object
Set MimeMapObj = GetObject("IIS://LocalHost/MimeMap")
' Call AddMimeType for every pair of extension/MIME type
For counter = 0 to UBound(MimeTypesToAddArray) Step 2
AddMimeType MimeTypesToAddArray(counter), MimeTypesToAddArray(counter+1)
Next
' Create a Shell object
Set WshShell = CreateObject("WScript.Shell")
' Stop and Start the IIS Service
Set oExec = WshShell.Exec("net stop w3svc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
Set oExec = WshShell.Exec("net start w3svc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
Set oExec = Nothing
' Report status to user
WScript.Echo "Windows Presentation Foundation MIME types have been registered."
' AddMimeType Sub
Sub AddMimeType(ByVal Ext, ByVal MType)
' Get the mappings from the MimeMap property.
MimeMapArray = MimeMapObj.GetEx("MimeMap")
' Add a new mapping.
i = UBound(MimeMapArray) + 1
ReDim Preserve MimeMapArray(i)
MimeMapArray(i) = CreateObject("MimeMap")
MimeMapArray(i).Extension = Ext
MimeMapArray(i).MimeType = MType
MimeMapObj.PutEx(ADS_PROPERTY_UPDATE, "MimeMap", MimeMapArray)
MimeMapObj.SetInfo()
End Sub
If you open the file with vim and use the ex command 'set list' it will show you any invisible characters that may be causing this issue.
Quoting http://classicasp.aspfaq.com/general/why-do-i-get-800a0408-errors.html
If you cut and paste code from other
sources (e.g. web sites, other
editors, etc) you often bring along
characters that don't show up in
Notepad but are, nonetheless, present
-- or do appear as non-prinatable characters, that look like little
squares. If you're looking at the line
in question and it isn't simply an
unclosed string or a premature
carriage return, try deleting the
line(s) altogether and re-typing them
by hand. This should eliminate the
possibility of 'invisible' problem
characters mucking up the stream.
Check the encoding when you save the file, must be ANSI in NotePad