programatically add module to xls 2003 using vbscript - excel

The first part is now working [
I have the following which just seems to hang; the part that adds/deletes the module works when running in VBA
I note that I'm prompted with a dialog saying 'this workbook contains links to other data sources' which I ok to, then it hangs
So I tried setting the second argument to 0 and also tried 2 but still it hangs
(2nd arg is UpdateLinks as can be found here )
]
dim objExcel
dim objWorkbook
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open( "H:\M\X\C.xls", 0 , , ,"PASSWORD!" )
Const modpath = "H:\M\V\"
Const modtest = "TEST.cls"
Const modname = "TEST"
On Error Resume Next
Dim vbcomp
Set vbcomp = ActiveWorkbook.VBProject.VBComponents(modname)
objWorkbook.VBProject.VBComponents.Remove vbcomp
objWorkbook.VBProject.VBComponents.Import modpath & modtest
objWorkbook.Save
objWorkbool.Close
set vbcomp = nothing
set objworkbook = nothing
set objExcel = nothing
edited again 14/04/2009
I have now also allowed the 'tools - macro - security - vbproject access'
The script now finishes, however, when trying to open the xls to see if the changes have been made, I get a message informing me that the sheet is locked by "account used to run script"; open 'read only'/notify
Why isn't it releasing control correctly**?**

First thought: Does your workbook already contain a reference (within VBA) to the "Microsoft Visual Basic for Applications Extensibility" library? You'll need it to be able to talk to the VBProject object. Actually, you probably do have the reference if your code works in VBA.
Second thought: ActiveWorkbook is probably not defined outside of an actual workbook. Try replacing it with your objWorkbook object.

Here's a third thought. Did you try setting the Application's DisplayAlerts property to FALSE before you include the module?

The edited script works.
The problem was caused by the fact that I was supplying the password at the workbook level and not at the VBA project level.
A quick search on the web reveals that it is not possible to do this anyway (sendkeys etc) so after manually removing the password on the project, the problem is solved

Related

VBA GetObject from Multiple Open Instances of Attachmate Reflection?

My company recently upgraded from Attachmate EXTRA! to Attachmate Reflection. We have a number of macros that ran on extra to screen scrape. Basically, you would press a button to start the macro, it would ask you to select which extra screen you wanted to run it on (we always have 3+ open for different systems), and then the macro would just use the most recently selected (active) session. Here's the code for that:
Private Function GetReflectionWindow(sessionName As String) As ExtraScreen
'Gets the most recent active reflection or extra window.
'Requires Reference: EXTRACOM
Dim sys As ExtraSystem: Set sys = CreateObject("EXTRA.System")
Dim sess As ExtraSession
'Set current sesion to most recently active session
If MsgBox("Click on the " & sessionName & " session and click 'OK' to continue.", vbOKCancel) = vbCancel Then End
Set sess = sys.ActiveSession
'Checks the session
If sess Is Nothing Then
MsgBox "Could not locate a Reflection or Extra session!", vbCritical
End
Else
Set GetReflectionWindow = sess.Screen
sess.Activate
End If
End Function
This no longer works for Reflection systems. Instead I've looked at this documentation here. The problem is that when you use CreateObject or GetObject, it only looks at the first open instance, not the active instance.
Sub GetNewReflectionWindow()
Dim App As Attachmate_Reflection_Objects_Framework.ApplicationObject
Dim screen As Attachmate_Reflection_Objects_Emulation_IbmHosts.IbmScreen
Dim Terminal As Attachmate_Reflection_Objects_Emulation_IbmHosts.IbmTerminal
Dim Frame As Attachmate_Reflection_Objects.Frame
Dim View As Attachmate_Reflection_Objects.View
Set App = GetObject(, "Attachmate_Reflection_Objects_Framework.ApplicationObject")
End Sub
I can't see anything in the documentation or object browser that would let me select the active session like Extra.System did.
I had the same issue and finally found the solution in the MicroFocus docs of all places! Accessing All Open "Reflection Workspace" Objects in VBA Macro Code
Basically, continue to use CreateObject to get the Workspace, but do it in a loop renaming each one as you go:
Dim oSession As Object
'find all open sessions
Do
Set oSession = CreateObject("Reflection Workspace")
oActiveSession.AutomationServerName = "Unused"
Loop
'rename sessions back to original
Do
Set oActiveSession = CreateObject("Unused")
oActiveSession.AutomationServerName = "Reflection Workspace"
Loop
I put this into its own function as the CreateObject throws an error when you run out of Workspaces.

Read live Values from one Excel Workbook to another Workbook while opened

I would like to be able to read and write values using VBA from one OPEN Excel workbook to another application without using the "as worksheet" function due to this being a non-windows application. Is this possible?
The code I've posted is from a PLC application using scripting.
I just need to know what function to use besides .open since the file is already opened.
Dim objXLApp, objXLWb, objXLWs1, objXLWs2, objXLWs5
Set objXLApp = CreateObject("Excel.Application")
objXLApp.Visible = True
Set objXLWb = objXLApp.Workbooks.Open("File.xlsm")
'~~> Working with Sheet1
Set objXLWs1 = objXLWb.Sheets(1)
Set objXLWs2 = objXLWb.Sheets(2)
Set objXLWs5 = objXLWb.Sheets(5)
'~~>Write SetPoints to Sheet1
With objXLWs1
'~~>Write
.Cells(6,23).value = SmartTags("Job Time Sec to OEE")
.Cells(6,23).value = SmartTags("Run Time Sec to OEE")
End With
''~~>Write Setup Values to Sheet2
'~~> Save as Excel File (xls) to retain format
objXLWb.Save
objXLWb.Close (False)
Set objXLWs1 = Nothing
Set objXLWs2 = Nothing
Set objXLWs5 = Nothing
Set objXLWb = Nothing
objXLApp.Quit
Set objXLApp = Nothing
If the workbook is already open you can just refer to it by name as part of the Workbooks collection.
Set objXLWb = objXLApp.Workbooks("File.xlsm")
Edit: Since you have changed your question I'm no longer certain what you're asking. My guess is that your 'already open' workbook isn't open in the same Excel instance you're creating with Set objXLApp = CreateObject("Excel.Application"), so you'll need a reference to the existing Excel application, then the open workbook within that application.

Bad Parameters in Selection (Excel VBA)

I need to copy/paste table from Excel to owrd to a specific line. I have written the code and it works fine in the Excel and Word 2016 I used, but when I tried running in other versions (2013,2010,2007) it didn't work at all. So i try to use late binding, but it throws a Bad Parameters error in .selection
How to remove Bad Parameters? Thanks,
Here's the code :
Sub Movetable ()
'Name of the existing Word document
Const stWordDocument As String = "Test.docx"
'Word objects.
Dim wdApp As Object
Dim wdDoc As Object
Dim wdRange As Object
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim xlRange As Excel.Range
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Worksheets("RJ").Select
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Set xlRange = Range("A4:D" & LastRow)
xlRange.Select
xlRange.Copy
'Instantiate Word and open the "Test" document.
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)
wdDoc.Application.Selection.Find.Execute "Table 1. Summary", MatchCase:=True
wdApp.Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdMove
wdApp.Selection.PasteExcelTable False, False, False
wdDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
wdApp.Quit
'Null out the variables.
Set wdRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
Very probably, the reason is that you've set a Refernce to the Microsoft Word library for version 2016. When you open and run the project in an earlier version, the reference doesn't change to the Microsoft Word library for that version. This is expected behavior.
To fix the problem you can either
Open the project in the earliest version of Office (2007,
apparently). Go to Tools/References in the VBA Editor and select the
Microsoft Word library for that version. Test, then save.
Office applications will change References to a newer version, but they don't do so the other way around. That's why it's always recommended to develop using the oldest version of Office the project should work in.
Don't use named arguments in the method calls. Remove, for example, MatchCase:=, Unit, Count, Extend. In addition, don't use the Word enumerations: wdLine, wdMove, wdAutoFitWindow- these all have numerical equivalents, use those instead.
This is known as "late-binding", which makes your project independent of the version of Word. You can then completely remove the Reference to the Microsoft Word library.
In order to find out the numerical equivalents you can look up the enumerations in the VBA Object Browser (F2 in the VBA Editor), look them up in the Word VBA Help or query them in the VBA Editor Immediate Window (Ctrl + G) using syntax like this: ?wdLine and then press Enter to execute.

Calling Workbooks.Open

This VBScript errs as "unknown runtime error", on the VBScript line that calls the application object's RUN method, which I'm quite sure I'm using correctly, syntactically.
With only one workbook open under the application object, I probably don't even need to prefix it with the Workbookname.
It appears the previous line (which sets the wb variable to the application object's Workbooks.Open method, does not open. Nor does it err, nor does it "eventually" open. The path is correct, the filename is correct, there is no On Error Resume Next in my VBScript.
How can the workbook not open and not error?
I hope I am wrong in thinking there is a "wait/pause" issue. Acting directly on the Excel object model, it seems like the VBScript code waiting until the excelapp object has opened the workbook should be a given?
dim excelapp, wb
set excelapp = createobject("excel.application")
excelapp.enableevents=true
excelapp.visible=true
set wb = excelapp.workbooks.open("C:\Users\John\Desktop\Scheduled Jobs from Isaac\Availability.xlsb")
'MSGBOX "SHOULD BE OPEN"
excelapp.windowstate = -4137 'value for constant xlMaximized acccording to msdn
excelapp.caption = "Running AVAILABILITY - Please WAIT..."
excelapp.run "Availability.xlsb!ChangeAndCopyFile"
final vbscript code i used, for better or worse:
dim excelapp, wb
'set excelapp = createobject("excel.application")
'excelapp.enableevents=true
'excelapp.visible=true
'set wb = excelapp.workbooks.open("C:\Users\John\Desktop\ScheduledJobsfromIsaac\Availability.xlsb")
'although I don't know why the above line is silently failing, i'm going to use an alternate method I read on S.O.:
set wb = GetObject("C:\Users\John\Desktop\ScheduledJobsfromIsaac\Availability.xlsb")
set excelapp = getobject(,"excel.application")
excelapp.enableevents=true
excelapp.visible=true
excelapp.windowstate = -4137 'value for constant xlMaximized acccording to msdn
excelapp.caption = "Running AVAILABILITY - Please WAIT..."
excelapp.run "Availability.xlsb!ChangeAndCopyFile"
wb.close(true)
excelapp.caption = "10 seconds to close - please WAIT..."
wscript.sleep 10000
excelapp.displayalerts=false
excelapp.quit
probably, it helps if you can describe where and how you execute your vbscript above? is this coded in a .vbs file and execute with wscript.exe or cscript.exe, or embedded in a HTML or HTA?
If this is scripted in HTML, what browser are you using to view that? Please take note that almost all modern browsers will just ignore the vbscript silently.

How to run VBScript GetObject while the computer is locked?

For a few reasons discussed here I can't open an excel worksheet like this:
Set excel = CreateObject("Excel.Application")
Set workbook = excel.Workbooks.Open(file_path.xls)
excel.Visible = True
So I'm trying to open it like this:
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
Set excel = GetObject(,"Excel.Application")
Set workbook = excel.Workbooks.Open( excel_file_path, 3)
excel.Visible = True
This runs just fine when my computer isn't locked. And usually VBScripts can run even when a computer is locked. However, only when the computer is locked, at the line GetObject(,"Excel.Application") I get the following runtime error:
Error: ActiveX component can't create object: 'GetObject'
Code: 800A01AD
Source: Microsoft VBScript runtime error
I tried changing my Windows 7 settings to never lock after some inactivity, but my company's IT department has enforced that setting.
Is there a way to run this script from a locked screen, or is there an alternative you recommend?
Edit:
It has something to do with the way the excel file is being opened... If I open a new blank excel page than lock the screen, GetObject will work just fine getting that document, but if I open it using the shell then log out, it won't...
In the section that does not seem to work, add this line after setting visible = TRUE, and see if your calculations then work as expected:
CreateObject("WScript.Shell").AppActivate objExcel.Name
Not sure if it will work, but I am doing similar things in some code and this is what's there.
I must have copied or read about it somewhere (wish I could give credit to where).
FYI - I have a vbscript that opens Excel, starts a new workbook, reads a file in as text via a querytable object, then does some automated edits. The code that works for me is:
...
set objExcel = CreateObject("Excel.application")
' Commented out the following line, so the user can see something is happening.
' objExcel.application.screenupdating = false ' Don't update the screen while shucking and jiving is going on.
objExcel.visible = true
objExcel.application.cursor = 2 ' change cursor to the hourglass.
CreateObject("WScript.Shell").AppActivate objExcel.Name
' Create a new workbook and worksheet
objExcel.workbooks.add
objExcel.worksheets.add
etc
Try the code:
CreateObject("WScript.Shell").Run "excel.exe """ & excel_file_path & """"
WScript.Sleep 5000
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
Set excel = GetObject(,"Excel.Application")

Resources