Excel VbScript Quotes issue - excel

I am using Vbscript to write some data into excel then i am saving this excel object as txt file. My problem here is after saving as text file some rows contains quotes ". Below is my code can some body help me recording this.
My Output text file is:
"Rules*V*ZBEA*892**0010*10*IBM-01**"
30,000.00*01/08/2012*21/08/2012****0000013556*01***2600
"Scale value* *********"
problem here is 1st and 3rd row starts and ends with quotes (" ").
code is
Dim objXL1,name
Set objXL1 = CreateObject("Excel.Application")
objXL1.Workbooks.Add
objXL1.Cells(1 ,1) = "Rules*V*ZBEA*892**0010*10*IBM-01** "
objXL1.Cells(2,1) = "30,000.00*01/08/2012*21/08/2012****0000013556*01***2600"
objXL1.Cells(3 ,1) = "Scale value* *********"
name = objXL1.GetSaveAsFilename(,"Text(MS-DOS)(*.txt),*.txt")
objXL1.ActiveWorkbook.SaveAs name ,21 ,,21
objXL1.ActiveWorkbook.Close 0
objXL1.quit
And here once more issue is I am using SaveAs method for getting file name. When execution comes to this line the file save dialog box hiding behind the main IE window is there any way to get this save dialog box in focus?

I assume this is because of the whitespace. In your code there is a trailing whitespace in the frist line.
"Rules*V*ZBEA*892**0010*10*IBM-01** "
-----------------------------------^-
If you would export multiple cells you would need to encapsualte those cells to recognize where a cell value begins and ends.

Related

printing txt file from VBA for Matlab

I am working parallel with Excel and VBA in order to create txt files I wish to use for MATLAB. However, I experience some format issues I can't resolve.
For instance, the following VBA
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, Sheets("Example").Cells(i + 3, 3)
Next i
Indeed prints numbers (reals) it is supposed to however MATLAB struggles with reading this example .txt file.
There are some characters VBA is printing. I don't know how to delete those within a VBA code.
Example.txt opened in matlab. Note the NaN read by MATLAB from a text file:
VBA text file - Note a line as the first element of a column
Perhaps there is a character that is invisible.
A possible solution is to remove those characters with regex.
Add reference to Microsoft VBScript Regular Expression 5.5
Then the following VBA code:
Set re = New RegExp
re.Pattern = "[^0-9]"
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, re.Replace(Sheets("Example").Cells(i + 3, 3).value, vbNullString)
Next i
This should remove anything that is not a digit from the cell before printing it to the text document.

VB .Net when exporting to CSV issue when viewing in MS Excel

I have encountered something really weird. When exporting to CSV my top line shows the quotation marks yet the lines below down.
I use UTF8 encoding and manually add the double quotation marks to the value so that it is encased with quotation marks.
the code being used is
Dim fs As New IO.FileStream(GenericValueEditorExportFilename.Value, IO.FileMode.Create)
Dim writer As New IO.StreamWriter(fs, Encoding.UTF8)
fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)
....
....
....
While reader.Read
If reader("TargetLanguageID") = targetLanguageID Then
writer.WriteLine(Encode(reader("SourcePhrase")) & ", " & Encode(reader("TargetPhrase")))
End If
....
....
....
Friend Shared Function Encode(ByVal value As String) As String
Return ControlChars.Quote & value.Replace("""", """""") & ControlChars.Quote
End Function
the result when displayed in excel is shown as (https://ibb.co/ntMYdw)
when i open the file in Notepad++ the text is shown as below. But each line is displayed differently. Why is it that the 1st row displays them and the 2nd does not. Notepad++ result is displayed as (https://ibb.co/fMkWWG)
Excel is treating the first line as headers.
https://stackoverflow.com/a/24923167/2319909
So the issue was being caused by the BOM that was created to manually set the encoding for the file as a start writing to the file.
fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)
Removing this resolves by issue and the file remains in the desired UTF8 encoding as it is set on the stream writer. so there is no need to add the BOM to set the encoding.
Something like this should work for you.
Dim str As New StringBuilder
For Each dr As DataRow In Me.NorthwindDataSet.Customers
For Each field As Object In dr.ItemArray
str.Append(field.ToString & ",")
Next
str.Replace(",", vbNewLine, str.Length - 1, 1)
Next
Try
My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", str.ToString, False)
Catch ex As Exception
MessageBox.Show("Write Error")
End Try

Removing unwanted data from text file

I have a large text file exported from an application that has three unwanted zeros in each row. The text file needs to be imported into another application and the zeros cause a problem.
Basically the unwanted three zeros per row need to be deleted. These zeros are always in the same location (same number of characters when counting from the left), but the location is somewhere in the middle. I have tried various things like importing the file into excel, removing the zeroes and then exporting as text file, but always have formatting problems with the exported text file.
Can someone suggest a solution or point me in the right direction?
something like this ? (quickly done)
Sub replaceInTx()
Dim inFile As String, outFile As String
Dim curLine As String
inFile = "x:\Documents\test.txt"
outFile = inFile & ".new.txt"
Open inFile For Input As #1
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, curLine
Print #2, Replace(curLine, "000", "", 6, 1, vbTextCompare)
Loop
Close #1
Close #2
End Sub
Alternatively, you can do that with any text editor that allows block selection (I like Notepad2, tiny, fast and portable)
I see you use excel a lot.
When you import the text file into excel do you use the import function and do you push the data into separate cells?
if the cell is numeric you could do the following:
=LEFT(TEXT(G5,"#"),LEN(TEXT(G5,"#"))-3)
if the cell is text:
=LEFT(G5,LEN(G5)-3)
G5 would the cell the data row/field is in.
curLine = Left(curLine, 104)
This will take the first 104 characters

Applescript Excel 2016 SAVE AS CSV

The Applescript below works fine without any issues in Excel 2011. The script opens an Excel file, deletes a column and removes any "," or ";" from the Excel file and then saves it as a CSV file. The issue I'm running into in Excel 2016 is the last piece to save it as a CSV file after the manipulation. Nothing is saved and I don't get any errors.
tell application "Microsoft Excel"
activate
open theWorkbookFile #open the xls file
set theWorksheetname to name of worksheet 1 of active workbook
set theWorksheet to worksheet 1 of active workbook
activate object theWorksheet
tell application "System Events" to set visible of process "Microsoft Excel" to false
#Remove the first column
tell theWorksheet
delete range column 1 shift shift to left
try
##remove any "," and ";" from the product description and replace it with a " " instead.
replace (range "B:B" of worksheet "Sheet1") what "," replacement " "
replace (range "B:B" of worksheet "Sheet1") what ";" replacement " "
end try
end tell
#Set the temp csv file to the name of of the Excel sheet followed by -TMP.csv
set theFile to theWorksheetname & "-TMP" & ".csv" as text
save as theWorksheet filename theFile file format CSV file format with overwrite #save the file in csv format and overwrite if it exist
close active workbook saving no #close the csv file without prompting user to save again
end tell
I came across the same issue and managed to save as CSV kind of "manually", using AppleScript to do the user interaction that the user should do.
My code is below...
#here you choose the name to your CSV file
set fileName to "ClearD -" & (current date) as string
#here you should have your original .XLSX file name and address to open it further
set theDoc to ((path to desktop folder as text) & "ClearD-Data.xlsx") as string
tell application "Microsoft Excel"
activate
open file theDoc
delay 1
tell application "System Events"
keystroke "s" using {command down, shift down}
delay 0.3
tell front window of (first application process whose frontmost is true)
click pop up button 2 of sheet 1
delay 0.3
#we are doing this to select CSV in the dropdown menu
repeat 3 times
keystroke "c"
end repeat
key code 36 # hit return
delay 1
repeat 50 times # this will delete whatever the current file name is and put fileName instead
key code 123 using {shift down}
end repeat
delay 1
#this will type your file name
keystroke fileName
delay 1
click button "Save" of sheet 1
-- set uiElems to entire contents # I use this command only to see what is out there for me to use and troubleshoot
end tell
end tell
#now we are all good so we will close excel
close active workbook saving no
end tell

Here is some Applescript code to interact with Microsoft Excel on Snow Leopard - How to add the missing functions

I have about 400 excel files. I want to insert a column just before the first column in the existing file and then insert the name of the file into each row of that column.
I know a little bit of Applescript and based on that I wrote this script so that I can drop some files onto the script and it will execute the script on each one of those files.
I was wondering if someone could help me in completing the "TO DO" lines. Upon execution this script gives me dialogue boxes with the path of files that I drop on top. But the excel application throws an error dialogue box which says" Not enough memory". I tried this with only 2 excel files so it wasn't the number of files that caused the error.
Can someone please give me a hand with completing the TODO lines and give me an ide as to why Im getting the error. Thanks
property numFiles : 0
on open excelFiles
set fileNames to ""
tell application "Finder"
repeat with eachFile in excelFiles
--open document file eachFile
--tell application "Microsoft Excel"
--increment count
--save name of each file
set fileNames to fileNames & return & (POSIX path of eachFile)
--TO DO insert a column
--TO DO insert text in each column to the name of eachFile
--end tell
end repeat
display dialog fileNames
--display dialog "Ouch that hurt " & return & "You dropped " & (count excelFiles) & "files on me"
end tell
end open
on addFilePath(eachFile)
set fileNames to fileNames & (POSIX path of eachFile)
end addFilePath
Thanks a lot
I don't understand everything --> insert the name of the file into each row of that column | TO DO insert text in each column to the name of eachFile.
Here is the script, Updated :
on open excelFiles
set numFiles to count excelFiles
repeat with eachFile in excelFiles -- open each file in Excel
tell application "Microsoft Excel"
set tBook to open workbook workbook file name (eachFile as string)
set tName to name of tBook
insert into range column 1 of active sheet -- insert column
set lastCell to last cell of used range of active sheet -- get last cell from the used range
set value of range ("A1:A" & first row index of lastCell) of active sheet to tName --set first column's values to the file name
close tBook saving yes
end tell
end repeat
display dialog numFiles
end open
Edit : I forgot the error :
Not enough memory : This weird error seems to be : you call a handler without using my or tell me to) in a tell block application.
Use my like this : set x to my addFilePath(eachFile)
Also, a tell application "Microsoft Excel" block in the application Finder block is not recommended, this can cause unexpected errors.

Resources