Write contents of immediate window to a text file - vba

I'm writing a macro which goes through a document and tries to parse it by Style. Right now, anything in the designated style is copied onto the immediate window. Is there a way to automate the macro further to move the text from the immediate window into a txt file? Otherwise, anyone using the macro would not be able to see the text unless they opened up VBA, correct?

Here's my suggestion: write to the immediate window AND to a file at the same time. Examples below.
Why make the information first transit in the immediate window, and only then write it to a file from there? That just sounds perversely and uselessly difficult!
Dim s As String
Dim n As Integer
n = FreeFile()
Open "C:\test.txt" For Output As #n
s = "Hello, world!"
Debug.Print s ' write to immediate
Print #n, s ' write to file
s = "Long time no see."
Debug.Print s
Write #n, s ' other way of writing to file
Close #n
Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject
Dim txs As Scripting.TextStream
Set txs = FSO.CreateTextFile("C:\test2.txt")
s = "I like chickpeas."
Debug.Print s ' still writing to immediate
txs.WriteLine s ' third way of writing to file
txs.Close
Set txs = Nothing
Set FSO = Nothing
Note that this last bit of code requires a reference to be set: Tools > References > checkmark at Microsoft Scripting Runtime.

Put this code to immediate window and hit enter to write the List to JSON text in C#.
System.IO.File.WriteAllText(#"C:\Users\m1028200\Desktop\Json2.txt",
JsonConvert.SerializeObject(resultsAll));

I would recommend to use some best-practices-based logging framework like VBA Logging, which supports file logging or console configurably in parallel etc.
example usage (e.g. in some Foo.bas module):
Sub MySub()
Logging.setModulName (Application.VBE.ActiveVBProject.Name)
Set log = Logging.getNewLogger(Application.VBE.ActiveVBProject.Name)
Call log.setLoggigParams(Logging.lgALL, True, True, True) ' log ALL to Console, Buffer, File
log.logINFO "This is my message ..", "MySub"
End Sub
resulting in something like (both in console and vba_logging.log file):
(16.12.2018 13:08:30)[XlsxMgr::MySub]-INFO: This is my message ..
where the log config file looks like this:
## vba_logging.properties
LOG_LEVEL = info
LOG_TO_CONSOLE = True
LOG_TO_BUFFER = True

Related

Writeline in VBA breaks with too long text

I am automating a web page extraction and writting the contents to a text (HTML) file.
For that I set up a File System Object like this
Dim myHTMLfilepath As String
myHTMLfilepath = "C:\temp\MyFile.html"
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim myHTMLFile As Object
Set myHTMLFile = fso.createtextfile(myHTMLfilepath)
When I try to write the extracted content to the file sometimes I get an error 5 (invalid parameter). Here is th code:
myHTMLFile.writeline objIE.document.getElementsByClassName("cool-box")(0).innerHTML
It breaks when the length of the innerHTML is somewhere between 25800 and 28000 (I haven't yet figured the exact limit).
Does anyone know if the WriteLine limit can be increased or advise on a different way to do this?
Assuming the .innerHTML can successfully be read into a string (split up reading/writing to find out), you should be able to use an ADODB.Stream to write it to the file. WriteLine is intended to write a single line of text to a file, not a whole entire document.
Dim contents As String
contents = objIE.document.getElementsByClassName("cool-box")(0).innerHTML
With CreateObject("ADODB.Stream")
.Open
.Type = 1
.Write contents
.SaveToFile myHTMLfilepath, 2
.Close
End With

How to Link a VBA code with opened ETABS OAPI?

a project on ETABS 2015 is open on my PC. I want to do some change and process on it by a VBA code automatically. but all the sample code that I found was like this:
Public Sub Example()
Dim SapModel As cSapModel
Dim EtabsObject As cOAPI
Dim FileName as String
Dim ret As Integer = -1
'create ETABS object
EtabsObject = CreateObject("CSI.ETABS.API.ETABSObject")
'start ETABS application
ret = EtabsObject.ApplicationStart()
'create SapModel object
SapModel = EtabsObject.SapModel
'initialize model
ret = SapModel.InitializeNewModel()
'open an existing file - If no file exists, run the Save example first.
FileName = "c:\CSI_API_temp\example.edb"
ret = SapModel.File.OpenFile(FileName)
This code just open a new ETABS in my PC. but my ETABS project is already running and I want to connect to it but I don't know how!
please help me.
Your sample code is basically and typically the one needed to open ETABS ITSELF and to initialize a new model,
ETABSObject = CreateObject("CSI.ETABS.API.ETABSObject") followed by the invocation of ApplicationStart method are the direct means for that.
If you refer to the ETABS API documentation file in the installation destination (e.g "C:\Program Files\Computers and Structures\ETABS 2015\CSi API ETABS 2015.chm" ) Under the section "Release Notes>Attaching to a manually started instance of ETABS", or if you see the same section from the link
http://docs.csiamerica.com/help-files/etabs-api-2015/html/3ceb8889-9028-4de3-9c87-69a12055ade7.htm
you'll find code (in VB.Net) close to what you aim to, but it will not work with vba, so, what you will simply do is this
'The ret variable, just for method invocation convenience
Dim ret As Integer
'Create an instance of the currently opened Program
Dim myETABSObject As ETABS2015.cOAPI
Set myETABSObject = GetObject(, "CSI.ETABS.API.ETABSObject")
'Create an instance to the model
Dim myETABSModel As ETABS2015.cSapModel
Set myETABSModel = myETABSObject.SapModel
'Now, after the "reference instances" are obtained
'Initialize the model (using the model's instance of course)
ret = myETABSModel.InitializeNewModel() 'default units in kip_in_F
'Set the model templete, which is "Blank"
ret = myETABSModel.File.NewBlank()
And You can normally proceed in your coding.
Note: 1- GetObject(CSI.ETABS.API.ETABSObject) method will raise an error if ETABS is not opened.
2- you still can use GetObject even if ETABS is not opened and if you want to open it from windows shell (like using command prompt to open programs instead of double clicking on their respective icons), but this of course needs some Error Handling and the use of "Windows Script Host Object Model".
3- The examples in the documentation (under the documented methods and properties) may not be complete in terms of initiating input data, in cases like this they are just to create an impression of how to use their respective methods and properties.
The code below does as you asked. It uses VBA to connect to a currently running instance of ETABS. Please note if you're running multiple instances of ETABS it may not attach to the one you want.
You'll need to add a reference to 'ETABSv1.tlb' to your VBA project. If you're using VBA Editor for Excel, on the Tools menu select References, then click Browse then add C:\Program Files\Computers and Structures\ETABS 19\ETABSv1.tlb
Sub Main()
'create API helper object
Dim myHelper As ETABSv1.cHelper
Set myHelper = New ETABSv1.Helper
'dimension the ETABS Object as cOAPI type
Dim myETABSObject As ETABSv1.cOAPI
Set myETABSObject = Nothing
'attach to a running instance of ETABS
'get the active ETABS object
Set myETABSObject = myHelper.GetObject("CSI.ETABS.API.ETABSObject")
'get a reference to cSapModel to access all API classes and functions
Dim mySapModel As ETABSv1.cSapModel
Set mySapModel = myETABSObject.SapModel
' DO YOUR WORK BELOW.
MsgBox "Do your work here."
' DO YOUR WORK ABOVE.
'clean up variables
Set mySapModel = Nothing
Set myETABSObject = Nothing
Exit Sub
ErrHandler:
MsgBox "Cannot run API script: " & Err.Description
End Sub
ETABS comes with API documentation that you can find in the installation folder. On my machine it is here: C:\Program Files\Computers and Structures\ETABS 19\CSA API ETABS v1.chm

NotesDocument.save() causing loss of rich text formatting

I have following code in an lotusscript agent that removes attachments from NotesDocuments. But NotesDocument.save() causes loss of rich text formatting (font, color). Is there any way to retain the formatting?
Sub removeAttachments_v2(doc As NotesDocument)
Dim session As NotesSession
Dim rtitem As Variant
Dim filename As String
Dim ans As Variant
Set session = New NotesSession
Dim richstyle As NotesRichTextStyle
Set richstyle = session.CreateRichTextStyle
richstyle.NotesColor = COLOR_BLUE
If doc.HasEmbedded Then
Set rtitem = doc.getfirstitem("Body")
If (rtitem.type = RICHTEXT) Then
ForAll object In rtitem.EmbeddedObjects
If (object.Type = EMBED_ATTACHMENT) Then
filename = object.source
Call object.remove
Call rtitem.AddNewLine( 2 )
Call rtitem.AppendStyle(richstyle)
Call rtitem.AppendText( "Attachemnt removed: " & filename )
Call doc.Save( True, True , True )
End If
End ForAll
End If
End If
End sub
Edit1: Initialize function
Sub Initialize
Dim db As New NotesDatabase("","")
Dim col As NotesDocumentCollection
Dim doc As NotesDocument
Call db.Open("", "C:\this\is\db\dir\test.nsf")
Set col = db.Alldocuments
Set doc = col.Getfirstdocument()
While Not ( doc Is Nothing )
Call RemoveAttachments_v2(doc)
Call doc.Save(False, False, False)
Set doc = col.GetNextDocument( doc )
Wend
End Sub
Despite of the fact, that you save the document for every attachment I cannot find any reason, why this should happen. I just copied your code in an agent, and it removes the attachments as desired and appends the text in blue...
No formatting is lost...
The error has to be somewhere else in your code, probably in the calling function.
OLD ANSWER (wrong due to own tests, just kept here as history):
The Problem here most probably is: you defined rtitem as Variant. And
getfirstitem gets you a NotesItem instead of a NotesRichtextItem, so
when saving, it is converted to a "plain Text" item.
Most probably you used Variant instead of NotesRichtextItem, because
there are Mime- mails where defining the variable as NotesRichtextItem
will cause an "Type Missmatch" or similar error. As long as you do not
write anything back this is OK.
As Mime Mails need complete different handling to achieve your goal,
you should first fix the code for pure NotesRichtextItems by using the
right type, and then write another code- branch for handling Mime-
items

Writing GMAIL inbox html to file fails (VBA, Textstream)

I retrieved a HTML file that I want to save using a textstream object from FileSystemObjects and it produces an empty file.
When I use MsgBox to display the stream right before the write command it shows all the HTML code I want, but it doesn't write the code to the file. Any suggestions?
Dim FSO As FileSystemObject
Dim FSOFile As TextStream
Dim FilePath As String
FilePath = "C:\myhtml.html"
Set FSO = New FileSystemObject
Set FSOFile = FSO.OpenTextFile(FilePath, 2, True)
FSOFile.Write myContent ' String object holding the HTML textstring
FSOFile.Close
I basically am trying to export my gmail inbox folder which I want to use as an event listener (so I can tell another machine what it is supposed to do.) .
On your comments so far:
- riteLine does not make any difference
- OpenTextFile creates non-existing files and it also creates the file and writes any other string that I manually type in, s.a. FSOFile.WriteLine "Nothing works"
- For completeness: CreateTextFile also did not help.
Any likely problem of writing the HTML code using the FSO stream?
Try WriteLine instead of just Write.
See Example: http://msdn.microsoft.com/en-us/library/aa242706%28v=vs.60%29.aspx

VBS Invalid Character

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