Need to generate excel using vb script? - vba

I am trying to run test cases using driver script, which i had developed in vb script.(below is some part of code that launches QTP), and lanuched qtp script generate XLS reports. now issue is that when i invoke test suite using vb driver script, it creates files which include result rows as well blank rows (upto 65635). this problem leads to result file(.XLS) sixed in MBs which should not include blank rows and must be in KBs.i also checked running test cases using QTP directly but i did not face any issues and size were in KB.
Dim qtApp, Test_Path
Dim BasePath
Dim qtTest
BasePath = "some path"
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch
qtApp.Visible = True
Test_Path = BasePath & "\" & scriptname
qtApp.Open Test_Path, True
Set qtTest = qtApp.Test
qtTest.Run
qtTest.Close
qtApp.Quit
Set qtTest = Nothing
Set qtApp = Nothing
kindly some one please let me know why the same script running using external VBs gives such huge result file?
Thanks in advance,
Priyank Shah

Implement the temp sheet creation in run time and generate the excel sheets. Also make sure that you set nothing on each excel object you declared.
Set objExcel = Nothing

Related

How to avoid runtime error 5152 when trying to add a URL as shape to a Word document

I am trying to place a QR code generated through an API (api.qrserver,com) in a Word table using VBA. For certain reasons, the option of simply using "DisplayBarcode" is not possible.
This is the call to the API:
sURL = "https://api.qrserver.com/v1/create-qr-code/?data=" & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+")) & "&size=240x240"
It seems to work well. I tried with a GET command and retrieved a string that - as I interpret - contains the QR code in png format.
Now, when I try to add the picture as a shape using
Set objGrafik = ActiveDocument.Shapes.AddPicture(sURL, True)
the call fails with runtime error 5152. As far as I could determine until now, the Addpicture method expects a pure filename and does not allow any of the following characters: /|?*<>:".
I also tried to store the GET result in an object variable:
Set oQRCode = http.responseText
but there I get the error "object required".
Research on the internet regarding a solution to either make the URL assignment work or to store the result as a picture didn't retrieve any useful results. Thanks in advance for your support
I am not sure that any of the ways you could insert something into Word (e.g. Shapes.AddPicture, InlineShapes.AddPicture, Range.InsertFile etc. will let you do that from any old https Url, although it seems to work for some Urls.
However, as it happens, you can use an INCLUDEPICTURE field to do it. FOr example
{ INCLUDEPICTURE https://api.qrserver.com/v1/create-qr-code/?data=Test&size=100x100 }
Here's some sample VBA to do that
Sub insertqrcode()
Dim sUrl As String
Dim f As Word.Field
Dim r1 As Word.Range
Dim r2 As Word.Range
' This is just a test - plug your own Url in.
sUrl = "https://api.qrserver.com/v1/create-qr-code/?data=abcdef&size=100x100"
' Pick an empty test cell in a table
Set r1 = ActiveDocument.Tables(1).Cell(5, 4).Range
' We have to remove the end of cell character to add the field to the range
' Simplify
Set r2 = r1.Duplicate
r2.Collapse WdCollapseDirection.wdCollapseStart
Set f = r2.Fields.Add(r2, WdFieldType.wdFieldIncludePicture, sUrl, False)
' If you don't want the field code any more, do this
f.Unlink
' check that we have a new inline shape that we could work with more
' if necessary
Debug.Print r1.InlineShapes.count
Set f = Nothing
Set r2 = Nothing
Set r1 = Nothing
End Sub
Using INCLUDEPICTURE works even on the current version of Mac Word (although I haven't tested that specific piece of VBA on Mac).
The only other way I have seen to do it uses WinHTTP to get the result from the web service, ADODB to stream it out to a local disk file, then AddPicture or whatever to include that file, so much more complicated and won't work on Mac either.

Error executing batch file in excel VBA windows

I was trying to execute a batch file via standard call shell() function.
This Batch file is project specific and created automatically for each project by an external application. Main function is to normalise around 40 files having statistical data used for my project. This data is being acquired form excel. While executing manually this takes around 30 seconds for the complete process and its working just fine.
When I try to access this using call shell function in VBA, It just pop up for like 2 seconds and outputs were not generated from Batch file.
I am attaching My sample code below used for this. I am just baby-stepping in VBA Macros. Please Excuse my coding practice.
Call Shell(Range("L8") & "\DSTAT$.BAT")
I tried this also
`Dim Runcc
Runcc = Shell(Range("L8") & "\DSTAT$.BAT", 1)`
Please let me know if any further information is required to sort this out.
Try
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
With CreateObject("WScript.Shell")
.Run Range("L8") & "\DSTAT$.BAT", windowStyle, waitOnReturn
End With
I use this for converting PDFs to JPG with Irfanview on report_open in Ms-Access.
Stolen from vba WScript.Shell run .exe file with parameter

Visual Basic - Getting basic information about another program

Alright, I am currently working on an Updater which is updating several files such as executable and drivers. I don't want to replace every single file every time I push an update and rather just replace the file that is actually getting updated. An easy way would be reading the Version of the program but I don't know how to read the required information. I went through IO.File but didn't find anything useful.
Try this for looping through a folder's files.
Option Explicit
Sub Macro1()
Dim varFile As Variant
Dim i As Integer
Dim objShell
Dim objDir
Set objShell = CreateObject("Shell.Application")
Set objDir = objShell.Namespace("C:\DIRECTORY_OF_FILES_HERE\")
For Each varFile In objDir.Items
Debug.Print objDir.GetDetailsOf(varFile, 156) ' 156 = File Version
Next
' Use this to see the numbers of all the attributes, e.g. 156 = File Version
'For i = 0 To 300
' Debug.Print i, objDir.GetDetailsOf(objDir.Items, i)
'Next
End Sub
You could create a separate file that will indicate the version of each individual files you will be updating. This is generally how I do things.
Say you have a file for this, we'll call it "version.txt". This is ideally what you would set it up like this: (you could do a lines format or javascript, whatever you feel most comfortable with)
mainapplication.version = 2.1
So, in your updater method, you would set the latest version as something like 2.2.
Dim alatestVersion As Double
alatestVersion = 2.2
You could then parse the text file and create a method to check if the component is of the latest version or not. Following this, if mainapplicationVersion != alatestVersion then [update].
Hope this helps.

Unused function in Excel addin causes crash only on second run and when run via VBScript

Sorry for the long title.
I have several .xlsm files which share a lot of code, so I moved the repeated parts to an addin .xlam file. I have been using a .vbs script to open all the files one after another and run a macro in each.
Problem
The problem I'm facing is that on the second run of the .vbs script, excel crashes and gives what seems to be a very generic error, said here to be an "Automation Error":
Script: C:\Users\~\Desktop\test\test.vbs
Line: 5
Char: 1
Error: The server threw an exception.
Code: 80010105
Source: (null)
To my surprise, I was able to reproduce this crash even after removing 99% of the content of my files.
test.vbs:
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Users\~\Desktop\test\test.xlsm")
xlApp.Run "Auto.Run" '<~~ error on this line
xlBook.Save
xlBook.Close (True)
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
test.xlsm:
test.xlam has a module Module1, test.xlsm has a Module Auto and a Reference to test.xlam
test.xlsm, Auto:
Sub Run()
MsgBox "hello"
Test.Load
MsgBox "goodbye"
End Sub
test.xlam, Module1
Sub Load()
MsgBox "Load"
End Sub
Function Other()
End Function
With the function Other() commented out, the code works fine (saying hello, load and goodbye). It also works fine if the macro is run from within excel. Only when Other() is present, and Run() is run through the .vbs file is there an error (right after hello).
Workaround
If I open test.xlsm, save it, and close it again in between each run of test.vbs, there are no problems. I believe this has something to do with the addin, rather than the spreadsheet, because in my original script, which opened multiple excel files, only one file needs to be opened and saved.
I also noticed that the excel file is a little bigger in its "problem" state, and that once I open and save it, it returns to its slightly smaller original size. (EDIT: This is at least partly caused by new cache streams __SRP_4 and __SRP_5 inside the vbaProject.bin file, which I extracted using this answer (oh, and this). After manually deleting all SRP entries, I was able to run the .vbs script again without problems, although just like the open-save-close strategy, it's only temporary, and will then crash on the third run rather than the second.)
Question
Are addins not appropriate for shared code? May they not contain functions? Is there any way to work around this crash besides what I'm doing right now?
Any thoughts are appreciated.
It sounds to me like the first instance isn't being unloaded/released before the second instance is being called. Perhaps using the Application.Wait Method to wait a few seconds before each subsequent run in performed might help?
'Open file1
'Run macro from file1
'Close file1
Application.Wait(Now + TimeValue("0:00:10")) 'wait 10 seconds
'Open file1
'Run macro from file1
...
...
So on
To install your add-in to excel via vbscript you can use the following code
'Launch Excel
set objExcel = createobject("Excel.Application")
strAddIn = "ESP Assistant.xlam"
'~~> Path where the XLAM resides
SourcePath = "Your source path\" & strAddIn
'Add the AddIn
On Error Resume Next
With objExcel
'Add Workbook
.Workbooks.Add
'Show Excel
objExcel.Visible = True
.AddIns.Add(SourcePath, False).Installed = True
End With
If this fails you might have to clear your registry values first, then rerun the above script
'File to use just in case Add-In installation fails
'Refreshes Excel Registry Entries to allow for clean install of Add-In
Dim objFSO, objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = WScript.CreateObject ("WScript.shell")
objShell.Run "cmd /c ""C:\Program Files (x86)\Microsoft Office\Office14\excel.exe"" /unregserver && timeout /t 3 && tskill excel && ""C:\Program Files (x86)\Microsoft Office\Office14\excel.exe"" /regserver",1,True
Set objFSO = Nothing
Set objShell = Nothing
x=msgbox("Excel registry refreshed." ,0, "Registry Update")
wscript.quit
Unfortunately, I still don't know why this is happening, but I found an automated solution that I'm going to stick with.
As I mentioned in my question, the test.xlsm file was a little bigger in its "problem" state, due at least partially to some kind of cache, of which I could only find one offical mention here:
2.2.6 SRP Streams
Streams that specify an implementation-specific and version-dependent performance cache. MUST be
ignored on read. MUST NOT be present on write.
The name of each of these streams is specified by the following ABNF grammar:
SRPStreamName = "__SRP_" 1*25DIGIT
My solution was to remove the cache, which I did manually at first with this tool. When that seemed to work, I wrote a Java program to do it automatically (gist here). It's glue between java.util.zip and Apache POIFS.
I also added a line to call the Java at the end of the .vbs script:
CreateObject("WScript.Shell").Run "java -jar clear-excel-cache.jar C:\Users\~\Desktop\test\test.xlsm", 1, false
In my actual .vbs file, which calls multiple excel files in a loop, this line is just inside the loop. There is a little cmd window that opens after each file is run but it no longer crashes on the second run, so I'm calling that a success.
Your issue could be the same issue which I am trying to resolve - Random 64-bit Excel 2013 VBA crashes (VBE7.dll errors). You can check the Application Event logs for a VBE7.dll crash to confirm this.
In my case various XLSM files become intermittently corrupted through manual use.
My fix as an alternative to yours is the following VBS (anything to trigger a VBA "recompile").
Resave "myfile.xlsm"
Sub Resave(filename)
Set objExcel = CreateObject("Excel.Application")
currentDirectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
objExcel.Application.AutomationSecurity = 3 ' Disable to avoid crash
objExcel.Application.enableevents = False
objExcel.Application.Workbooks.open(currentDirectory + "\" + filename)
objExcel.Application.Visible = True
objExcel.Application.DisplayAlerts = False
Set objSheet = objExcel.ActiveWorkbook.Sheets.Add
objSheet.Delete
objExcel.Application.DisplayAlerts = True
objExcel.Application.enableevents = True
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
Set objExcel = Nothing
End Sub
FYI - Microsoft released a patch which fixes the issue in Excel 2013 on 3rd May 2016.
https://support.microsoft.com/en-us/kb/3085486

The x command does not correctly when invoked under SASWorkspaceManager.WorkspaceManager?

I have written some SAS code that calls R via the x command (I am using SAS 9.1.3 so there is no native SAS interface to R).
OPTIONS XWAIT XSYNC;
X """&r_path."" --no-save --quiet < ""&out_code_folder.\code.r"" > ""&out_code_folder.\abba.log""";
This code works correctly when I run it in the SAS IDE but when I try to run the same code in VBA using (here strSAScode contains the above mentioned SAS code).
Dim obWM As SASWorkspaceManager.WorkspaceManager
Dim temp_dispaly_alert As Boolean
Dim sm As SAS_Management
Debug.Print strSASCode
Set sm = New SAS_Management
'Set obServerDef = New SASWorkspaceManagerServerDef
Set obWM = New SASWorkspaceManager.WorkspaceManager
Set obSAS = obWM.Workspaces.CreateWorkspaceByServer("MyServerName", VisibilityProcess, Nothing, "", "", "")
Set sm.obLS = obSAS.LanguageService
temp_dispaly_alert = Application.DisplayAlerts
Application.DisplayAlerts = False
sm.obLS.Submit strSASCode
Now every other code works, except the x command. Please Help.
By default, use of SYSTEM and X commands is disabled when accessed via techniques that use integration technologies due to potential security risks.
Have you followed the steps for 9.1.3 on Windows described in this usage note?
It describes how to enable this functionality on your SAS server; you may need to adapt what's described for the workspace, instead of the stored process, server.