Close Excel Workbook from VBA/JScript without crashing Excel - javascript

in VBA, I have a global script control variable in JScript language (Javascript ES3). I have the var "ThisWorkbook" set as
var ThisWorkbook = GetObject('', 'Excel.Application').Workbooks('" + ThisWorkbook.Name + "')
Then I can close the workbook by saying
ThisWorkbook.Close(false)
Full VBA code for completion:
Sub Test
Dim ScriptC as Object
Set ScriptC = CreateObject("ScriptControl"): ScriptC.Language = "JScript"
ScriptC.Eval "var ThisWorkbook = GetObject('', 'Excel.Application').Workbooks('" + ThisWorkbook.Name + "')"
ScriptC.Eval "ThisWorkbook.Close(false)"
End Sub
However, this crashes my Excel and all open workbooks (Excel 2016) - what would be a good way to avoid this? I have to do this from JScript/Javascript, but could for example do it through a WScript variable (as long as it's called from within JScript). The reason for this is that it's triggered by an event that's evaluated in JScript and not in VBA (VBA is just the wrapper in this case).
I've tried "ThisWorkbook.Application.Quit' (as per https://learn.microsoft.com/en-us/office/vba/api/excel.application.quit ), but that doesn't work either.
Thanks!

This bug only occurs when running the command from the immediate window - if run from within a subroutine it does NOT crash.
I had tested in immediate a bunch of times before realizing this.
Non-issue, apologies.

Related

ActiveXObject("Outlook.Application") Not working when Outlook is open

I have a javascript that works when Outlook is closed. However, if outlook is open I receive "Automation Server" error.
var outlookApp = new ActiveXObject('Outlook.Application');
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
email = mailFolder.Items.add('IPM.Note.FormA');
email.Subject="Quote: "+ quoteNum + ' | Part#: '+ partNum;
email.To = "lcarreiro#epectec.com"; //who will to be going to
email.HTMLBody = "Quote Attached " + quoteNum;
email.display(0);
Any suggestions besides changing IE setting as I have already done so....
Probably a little late to help you but hopefully it helps anyone else who ends up here.
I was having the same issue and stumbled across https://stackoverflow.com/a/3779945/1002621 which answered a similar question.
Basically the issue is because when you run Visual Studio as an Administrator and Outlook with normal privileges you are no longer allowed to get an instance to the existing Outlook application but as it is single instance it won't create a new one.
This is only an issue if you initiate debugging directly from Visual Studio just starting your own instance of IE makes the problem go away.

Cannot find source of javascript function call

Ok, so I need to find the source code of a particular javascript function on a website. (The specifics do not really matter unless there is no way to do what it is that I am asking)
I can see the function call in a link of html code
onclick="inbox.sendMessage();"
I know that the function does work because if I use a plugin a can call the function on that page, however, I have searched every .js file is referenced in that page, and none of them contain a function called sendMessage.
What I am asking is, is there a way to follow the code back to the source, perhaps if there was a way to debug the html and break when the onclick is triggered and then step into the function to see its source, but I do not know how I can do that or if it is even possible. Any help will be greatly appreciated, Thanks.
I guess you could do :
inbox.sendMessage
In the webconsole. (the function name without the parenthesis)
It will print out the source code of the function.
I usually use Opera, and in that at least this is what I do:
Open Opera Dragonfly (Ctrl + Shift + I).
Click on the HTML tag with the onclick handler.
Go to the listeners tab in the right hand side column.
See the listener for the click event. It shows you the file and line number.
sendMessage could be declared as:
var inbox{
sendMesssage:function(){
}
}
//or
function inbox(){
this.sendMessage=function(){
}
}
// or
inbox.sendMessage=function(){}
// or ...
So looking for "sendMessage(" or "function sendMessage" will not find you anything.
In chrome, Internet Explorer and Firefox (with firebug) you can hit F12 and go to debug, there you can check the scripts that have been loaded as there might have been scripts loaded dynamically.
#!/usr/bin/env ruby
Dir::glob("*").each do |name|
lineCount = 1
File.open(name, "r").each do |line|
puts "\nFile name: " + name + "\nline: " + lineCount.to_s if line =~ /inbox.sendMessage/ && name != "findfunction.rb"
lineCount += 1
end
end
Wrote a quick ruby script to help you out. To execute, first make sure you have a ruby interpreter on your machine then place the script in the directory with all your relevant files. load up a command line terminal, navigate to said directory and type "ruby findfunction.rb".
It will tell you all instances (files + line number) of "inbox.sendMessage".

ReferenceError: "document" is not defined

Im new to JavaScript and even more new to Google Apps Script. Im trying a simple function that shows the current date (only day, month e and full year), but the Google Script show the error ReferenceError: "document" is not defined.
My goal is to use this function in a Google Site. Here is the code:
function Data()
{
var d=new Date();
var dia=d.getDate();
var mes=d.getMonth();
var ano=d.getFullYear();
var DataCompleta=dia + "/" + mes + "/" + ano
document.write(DataCompleta);
}
Code running as a Google Apps Script does not run in the browser, so you cannot use web browser APIs with it. If you want to output content to a Google Site, then you need to use the API for Sites.
Presumably you would want something like createWebPage and then use the methods on the resulting object to add the content to it.
As said in the former answer you can't execute a function directly in the Browser, you'll have to choose a so called 'container' to run your function from it. I would recommand you read the documentation and maybe try a few simple tutorials to see how GAS can be executed.
EDIT : following your comments, feel free to have a look at this script built with UiApp, the result is viewable here and shows what you wanted to : "Hello, today is 25/10/2012"

How to use Javascript to check active directory to see if a user is in a memberof a particular group?

I have at my disposal Javascript and Classic ASP. Using these two how can I check to see if a user is a member of a particular active directory group? I know VBSCRIPT has memberof function but I can only use javascript. Any help is appreciated
You'll need to ensure that your web server is set to use Windows Authentication. Then you can use Request.ServerVariables("LOGON_USER") to get the current user's domain\username.
You'll then query Active Directory using ADSI to get group membership.
Here's a link to msdn's ADSI pages. http://msdn.microsoft.com/en-us/library/aa772170%28v=vs.85%29.aspx
This page has some sample scripts (in vbscript)
As far as I know there is no possibility to access activeDirectory by using Javascript. Javascript runs within the browser - and may not access anything out of this sandbox.
In case I misunderstood your question und you ment server-side checking - use ASP functions to check for.
You might also try using Javascript to instantialte a WScript.Network object
var WshNetwork = new ActiveXObject("WScript.Network");
From there, you can get
var netWorkUserName = WshNetwork.UserName;
var netWorkDomain = WshNetwork.UserDomain;
A word of warning: I'm pretty sure this is IE only and requires security changes in IE.
You'll need AJAX and a connection to the AD using ADODB.Connection with the "ADsDSOObject" provider.
EDIT: I saw your comment above. Here's a start:
ldapCommand.CommandText = "select sn from '" & _
"LDAP://example.com/DC=example,DC=com" & _
"' WHERE samAccountName=" & "'" & username & "'"
Set ldapRecordSet = ldapCommand.Execute
ldapCommand is an ADODB.Command, and if Execute throws an error, then the user is not in the domain.

How can I execute Javascript in my Delphi program without TWebBrowser?

I am working with a Web API that uses a Javascript interface to make requests, and the response is via a callback Javascript function. Is there a way to call Javascript code from Delphi without using a TWebBrowsercomponent?
You can always run cscript.exe on windows machines.
Advantages:
It's available on all default windows installs since windows 98.
It's dead easy.
No third-party Delphi components needed.
No dll's + wrappers needed, so deployment is simple.
Disadvantages:
You'll be spawning new processes. Starting cscript.exe on a web server feels wrong. I'm not sure what the security implications are.
You don't have direct access to the internals of the scripting engine.
Example program (it's just a proof-of-concept.. there are probably better ways to do this):
program JsExample;
{$APPTYPE CONSOLE}
uses Windows, IoUtils;
// start a new process
function RunProgram(const aProg, aParams: string; aHow2Show: Word; const aWaitTime: dword): boolean;
var LProcInfo: TProcessInformation; LStartUpInfo: TStartupInfo;
begin
FillChar(LStartUpInfo, SizeOf(TStartupInfo), #0); FillChar(LProcInfo, SizeOf(TProcessInformation), #0);
with LStartUpInfo do
begin
cb := SizeOf(LStartUpInfo);
lpReserved := nil; lpDesktop := nil; lpTitle := nil; lpReserved2 := nil; cbReserved2 := 0;
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := aHow2Show;
end;
Result := CreateProcess(nil, PChar(aProg + ' ' + aParams), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, LStartUpInfo, LProcInfo);
if Result then
Result := WaitForSingleObject(LProcInfo.hProcess, aWaitTime) <> WAIT_FAILED;
end;
// run javascript code
procedure RunJs(const aJavaScript: String);
var LTmpFileName: String;
begin
LTmpFileName := TPath.ChangeExtension(TPath.GetTempFileName, '.js');
try
TFile.WriteAllText(LTmpFileName, aJavaScript);
RunProgram('cscript', '/NOLOGO "' + LTmpFileName + '"', SW_SHOWNORMAL, INFINITE);
finally
TFile.Delete(LTmpFileName);
end;
end;
// main
begin
// execute some stupid javascript sample code
RunJs
(
'var Text="Hello from JavaScript!";' + // creating a js variable
'for(var i=0;i<Text.length;i++)' + // creating a js looop
' WScript.Echo(Text.charAt(i));' // calling string.charAt() and print some stuff
);
ReadLn;
end.
This method is really simple.. write the JavaScript to a file, then call cscript.exe with the filename as a parameter.
SpiderMonkey
V8
No clue if any of this actually (still) works though.
Are you looking for a JavaScript engine? There are some on the market, such as FastScript, and also I saw a Delphi wrapper for Windows Scripting Host (which has JavaScript support). Note, though, that if your scripts use web- and browser-related classes and functions, no engine except browser-based one will be able to offer them.
Is there a way to call Javascript code from Delphi without using a
TWebBrowsercomponent?
Yes, other way to use JavaScript wrapper for SpiderMonkey (FireFox) javascript engine.
http://code.google.com/p/delphi-javascript/
Required only 1 DLL. Compatible with XE2/XE4/XE5. Ready for x86 and x64 systems.
Usame sample:
Can I execute a Javascript function inside Spidermonkey and get the return value?

Categories

Resources