How to read an Excel file from VBScript? - vbscript

I am trying to read an Excel file in VBScript, but in the file.Readline I am getting strange characters. Do you have any idea how you could get the value of the cells correctly? Without Excel libraries.
Dim fso,file
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("C:\myFile.xlsx",1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close

if you are writing a macro in excel (Also visual basic script) there are more than one way getting a cell value.
There are range function
(example from web:) Worksheets("Sheet1").Range("A5").Value
There is cells function (example from web) Cells(1, 1).
The excel file (xslx) should be actually zip file where data is xml.
I think thats why you can't read it if you are using VB compiler.

You most likely need to have set the encoding for the page to UTF-8. See the links before for a simple description:
Classic ASP text substitution and UTF-8 encoding
https://www.w3schools.com/asp/prop_charset.asp
So it would look something like below, located near the top of the page:
Response.Charset = "UTF-8"

I have solved my problem using the extension .CSV, since this allows me to read the information as a .txt in which each column is separated with commas by default, so my code works normally.

Related

Need to strip out invalid characters in CSV file

I am generating a CSV file from a Microsoft SQL database that was provided to me, but somehow there are invalid characters in about two dozen places throughout the text (there are many thousands of lines of data). When I open the CSV in my text editor, they display as red, upside-down question marks (there are two of them in the attached screenshot).
When I copy the character and view the "find/replace" dialog in my text editor, I see this:
\x{0D}
...but I have no idea what that means. I need to modify my script that generates the CSV so it strips these characters out, but I don't know how to identify them. My script is written in Classic ASP.
You can also use RegEx to remove unwanted characters:
Set objRegEx = CreateObject(“VBScript.RegExp”)
objRegEx.Global = True
objRegEx.Pattern = “[^A-Za-z]”
strCSV = objRegEx.Replace(strCSV, “”)
This code is from the following article which explains in details what it does:
How Can I Remove All the Non-Alphabetic Characters in a String?
In your case you will want to add some characters to the Pattern:
^[a-zA-Z0-9!##$&()\\-`.+,/\"]*$
You can simply use the Replace function and specify Chr(191) (or "¿" directly):
Replace(yourCSV, Chr(191), "")
or
Replace(yourCSV, "¿", "")
This will remove the character. If you need to replace it with something else, change the last parameter from "" to a different value ("-" for example).
In general, you can use charmap.exe (Character Map) from Run menu, select Arial, find a symbol and copy it to the clipboard. You can then check its value using Asc("¿"), this will return the ASCII code to use with Chr().

Read File byte after byte in vbscript

I am looking for a way to read a big binary file using VBScript (big - 1 GB). I can't read it directly with ReadAll function because the file is too big, so I am looking for a way to read it in a loop, like in C. So I want to read X bytes, process them (I don't need the full file to do my stuff), then read next 10 and over again.
The problem is that I can't find a way to do that, I know how to start reading from offset, but can't find a way to read X bytes, there are only ReadAll and ReadLine functions.
Is there a way to read X bytes?
When in doubt, read the documentation:
Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
Syntax
object.Read(characters)
Arguments
object
Required. Always the name of a TextStream object.
characters
Required. Number of characters you want to read from the file.
filename = "C:\path\to\your.file"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
buf = f.Read(10)
'...
Loop
f.Close
Note, however, that the Read() method doesn't read bytes per se, but characters. Which is roughly the same as long as you open the file in ANSI mode (the default).

Create a new Word document without invoking Word

I want to write a VBScript that will create a new Word document in the current directory. I've tried this sort of thing:
Set word = CreateObject("Word.Application")
Set document = word.Documents.Add()
document.SaveAs(filename)
It basically works, but I want to do it without invoking the Word application.
When I right-click in a File Explorer window, I get a pop-up menu that includes a "New" option from which I can select "Microsoft Word Document". This creates a new Word document in the current directory without invoking the Word application, and this is the action that I would like to perform in my VBScript.
Does anyone know how I can write that?
As a workaround, my existing VBScript copies an existing blank Word file to the current directory. This works pretty well. The one drawback is that the newly created file has the creation time and/or last-modified time of the original file. How can I "touch" the newly created file (again, without invoking Word) so that it appears to have been created "right now"?
What the New → Microsoft Word Document context menu entry does is basically a combination of your workaround and the answer Robin Mackenzie provided.
New document creation via the Explorer context menu is governed by these registry keys:
HKCR\.doc\Word.Document.8\ShellNew (Word 97/2003 documents)
HKCR\.docx\Word.Document.12\ShellNew (OOXML documents)
…
If the keys contain a string value FileName and the directory %windir%\ShellNew contains a file winword8.doc (for Word 97/2003 documents) and winword12.docx (for OOXML documents) the new document will be created as a copy of that file.
If no matching file exists in %windir%\ShellNew or the registry key contains an empty string value NullFile instead of the value FileName, new files will be created as a zero-length files (basically empty ANSI text file). Word automatically converts these files when opening them.
If the registry key contains neither a value FileName nor a value NullFile no context menu entry is displayed for the given file type.
If your script just needs to create a new empty document without any particular content or formatting I'd go with the approach Robin suggested. Otherwise stick with your current method of copying a template file.
You can try this which creates an empty text file and changes the extension to .docx. It's not a 'proper' empty docx file, but it will open as a blank new Word document.
Dim objFSO, strDoc, objFile
' create object to interact with file system
Set objFSO = CreateObject("Scripting.FileSystemObject")
'name of word doc to create
strDoc = "D:\test.docx"
' create blank file and close
Set objFile = objFSo.CreateTextFile(strDoc)
objFile.Close
' clean up
Set objFile = Nothing
Set objFSO = Nothing

Populating an email with data from IBM i (AS400) screen

I'm trying to grab data from an AS400 screen & populate an email using that data but seem to have bumped into something I'm struggling to overcome. Here's a slice of what I have so far:
Dim polNo
polNo = GetText(10,18,10)
Dim wsh
Set wsh=CreateObject("WScript.Shell")
subSub1_()
sub subSub1_()
// Just doing this to check the text I have
SendKeys(polNo)
// Sent the eMail with the text
wsh.Run "mailto:testing#somemailbox.com?Subject=" & polNo
end sub
With the above, the resulting email subject line takes only the first word upto the first space. From what I've found, this is a parsing issue & have discovered the following line that should help.
polNo = Chr(34) + Replace(polNo,chr(34),chr(34)&chr(34))
The above line places all of the text in quotes (I know this because my SendKeys line now shows the GetText result with a " at the start.
The issue is when I reach the mailto line as Outlook pops up a window saying:
"The command line argument is not valid. Verify the switch you are using."
My end result will be an email that has a subject & a body with text taken from various parts of the screen.
Solved: Thanks to dmc below, he started me on the right line.
However, the solution was not to use Chr(34) but to use something as simple as:
polNo = Replace(polNo," ","20%")
Although it might not look like it, you're constructing a URL. As such, the contents of that URL must be URL Encoded. Certain characters can't be included in a URL, including a space. Those characters are represented with a percent sign followed by the ASCII code of the character in hexadecimal. For example, a space is changed to %20.
See the link below for a VBScript routine that will URL encode and decode strings.
http://www.justskins.com/forums/wsh-equivalent-of-server-38778.html
Edit: Although this is commonly known as URL encoding, the thing you're constructing is technically a URI. Wikipedia has a good page that explains further.

Replace word text with excel percentage value via VB returns text value on mac

I have following part of the code which replaces word text with value from excel:
.Replacement.Text = exlDoc.Worksheets(sheetName).Cells(row, column)
Excel values have General or Percentage format. On Windows, this works as expected, percentages are replaces as e.g. 5.54% while same code on Mac returns 0.0554. How can I format it to work on both Mac and Windows and to be working for all formats.
Thanks
You could change the number format in code.
ActiveCell.Numberformat = ??Percent
Try:
.Replacement.Text = exlDoc.Worksheets(sheetName).Cells(row, column).Text
.Text is a read-only property of the cell.

Resources