Solved

How do run a vbscript from vba while referencing activeworkbook

Posted on 2011-09-16
8
546 Views
Last Modified: 2012-05-12
I have an expertly developed script from Rob that sendkeys to the name manager in excel. It currently picks a file, deletes the names and stops. I'd like to run it after a vba macro.

My goals
display all names in active workbook
delete all the names that can be deleted from vba
run the vbscript to delete the remaining names through sendkeys on the Name Manager

Please refer here: http:/Q_27308727.html#a36553093 for a sample file so you know what I'm dealing with.

Thanks,

Thomas

Sub Display_All_Names_in_Workbook_Delete()
Dim nmName As Name

On Error Resume Next
For Each nmName In ActiveWorkbook.Names
    nmName.Visible = True
    nmName.Delete
Next

End Sub

Open in new window

Set myExcelWorker = CreateObject("Excel.Application")

' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False

myExcelWorker.Workbooks.Open(GetFileName( "", "*.xlsx;*.xls;*.xlsxm"))

Set oWB =myExcelWorker.ActiveWorkbook
myExcelWorker.Visible=True

intNames = oWB.Names.Count

strTempScript = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "DeleteNamesTemp.vbs"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objScript = objFSO.CreateTextFile(strTempScript, True)
objScript.WriteLine "WScript.Sleep 5000"
objScript.WriteLine "Set WshShell = CreateObject(""WScript.Shell"")"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{DOWN}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "For i = 1 to " & intNames
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""%D"""
objScript.WriteLine "WScript.Sleep 250"
objScript.WriteLine "WshShell.SendKeys ""{DOWN}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{UP}"""
objScript.WriteLine "Next"
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{ESC}"""
objScript.Close


Set WshShell = CreateObject("WScript.Shell")

WScript.Sleep 100
WshShell.SendKeys "^{F3}"
WScript.Sleep 200

WshShell.Run "wscript.exe """ & strTempScript & """", 1, True

objFSO.DeleteFile strTempScript, True


Function GetFileName( myDir, myFilter )
' This function opens a File Open Dialog and returns the
' fully qualified path of the selected file as a string.
'
' Arguments:
' myDir is the initial directory; if no directory is
' specified "My Documents" is used;
' NOTE: this default requires the WScript.Shell
' object, and works only in WSH, not in HTAs!
' myFilter is the file type filter; format "File type description|*.ext"
' ALL arguments MUST get A value (use "" for defaults), OR otherwise you must
' use "On Error Resume Next" to prevent error messages.
'
' Dependencies:
' Requires NUSRMGRLib (nusrmgr.cpl), available in Windows XP and later.
' To use the default "My Documents" WScript.Shell is used, which isn't
' available in HTAs.
'
' Written by Rob van der Woude
' http://www.robvanderwoude.com

    ' Standard housekeeping
    Dim objDialog

    ' Create a dialog object
    Set objDialog = CreateObject( "UserAccounts.CommonDialog" )

    ' Check arguments and use defaults when necessary
    If myDir = "" Then
        ' Default initial folder is "My Documents"
        objDialog.InitialDir = CreateObject( "WScript.Shell" ).SpecialFolders( "MyDocuments" )
    Else
        ' Use the specified initial folder
        objDialog.InitialDir = myDir
    End If
    If myFilter = "" Then
        ' Default file filter is "All files"
        objDialog.Filter = "All files|*.*"
    Else
        ' Use the specified file filter
        objDialog.Filter = myFilter
    End If

    ' Open the dialog and return the selected file name
    If objDialog.ShowOpen Then
        GetFileName = objDialog.FileName
    Else
        GetFileName = ""
    End If
End Function

Open in new window

0
Comment
Question by:nutsch
  • 3
  • 2
8 Comments
 
LVL 39

Author Comment

by:nutsch
ID: 36554642
Mark, it was working in the preview and now it's no longer working.

T
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 36556015
Hi, instead of running the macro at all, why don't you put that macro code inside the VBS, so that you have all of the code in the VBS?

After this:
intNames = oWB.Names.Count

Open in new window


put this:
On Error Resume Next
For Each nmName In oWB.Names
    nmName.Visible = True
    nmName.Delete
Next

Open in new window



and that should be it!

Rob.
0
 
LVL 85

Expert Comment

by:Rory Archibald
ID: 36559402
Any chance of a sample file that is not corrupt but demonstrates the issue? The ones posted in that other question seem to work fine with normal delete methods.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 39

Author Comment

by:nutsch
ID: 36560973
This one should do it.

T
Sample.xls
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 499 total points
ID: 36563966
Slight correction, try this.

Regards,

Rob.
Set myExcelWorker = CreateObject("Excel.Application")

' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False

myExcelWorker.Workbooks.Open(GetFileName( "", "*.xlsx;*.xls;*.xlsxm"))

Set oWB =myExcelWorker.ActiveWorkbook
myExcelWorker.Visible=True

On Error Resume Next
For Each nmName In oWB.Names
    nmName.Visible = True
    nmName.Delete
Next 
Err.Clear
On Error GoTo 0

intNames = oWB.Names.Count

strTempScript = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "DeleteNamesTemp.vbs"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objScript = objFSO.CreateTextFile(strTempScript, True)
objScript.WriteLine "WScript.Sleep 5000"
objScript.WriteLine "Set WshShell = CreateObject(""WScript.Shell"")"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{TAB}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{DOWN}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "For i = 1 to " & intNames
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""%D"""
objScript.WriteLine "WScript.Sleep 250"
objScript.WriteLine "WshShell.SendKeys ""{DOWN}"""
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{UP}"""
objScript.WriteLine "Next"
objScript.WriteLine "WScript.Sleep 100"
objScript.WriteLine "WshShell.SendKeys ""{ESC}"""
objScript.Close


Set WshShell = CreateObject("WScript.Shell")

WScript.Sleep 100
WshShell.SendKeys "^{F3}"
WScript.Sleep 200

WshShell.Run "wscript.exe """ & strTempScript & """", 1, True

objFSO.DeleteFile strTempScript, True


Function GetFileName( myDir, myFilter )
' This function opens a File Open Dialog and returns the
' fully qualified path of the selected file as a string.
'
' Arguments:
' myDir is the initial directory; if no directory is
' specified "My Documents" is used;
' NOTE: this default requires the WScript.Shell
' object, and works only in WSH, not in HTAs!
' myFilter is the file type filter; format "File type description|*.ext"
' ALL arguments MUST get A value (use "" for defaults), OR otherwise you must
' use "On Error Resume Next" to prevent error messages.
'
' Dependencies:
' Requires NUSRMGRLib (nusrmgr.cpl), available in Windows XP and later.
' To use the default "My Documents" WScript.Shell is used, which isn't
' available in HTAs.
'
' Written by Rob van der Woude
' http://www.robvanderwoude.com

    ' Standard housekeeping
    Dim objDialog

    ' Create a dialog object
    Set objDialog = CreateObject( "UserAccounts.CommonDialog" )

    ' Check arguments and use defaults when necessary
    If myDir = "" Then
        ' Default initial folder is "My Documents"
        objDialog.InitialDir = CreateObject( "WScript.Shell" ).SpecialFolders( "MyDocuments" )
    Else
        ' Use the specified initial folder
        objDialog.InitialDir = myDir
    End If
    If myFilter = "" Then
        ' Default file filter is "All files"
        objDialog.Filter = "All files|*.*"
    Else
        ' Use the specified file filter
        objDialog.Filter = myFilter
    End If

    ' Open the dialog and return the selected file name
    If objDialog.ShowOpen Then
        GetFileName = objDialog.FileName
    Else
        GetFileName = ""
    End If
End Function

Open in new window

0
 
LVL 39

Author Closing Comment

by:nutsch
ID: 37257826
Thanks guys, sorry for the closing delay. Rob's solution is working fine.

T
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This script will sweep a range of IP addresses (class c only, 255.255.255.0) and report to a log the version of office installed. What it does: 1.)      Creates log file in the directory the script is run from (if it doesn't already exist) 2.)      Sweep…
Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come…
This Micro Tutorial will demonstrate the scrolling table in Microsoft Excel using the INDEX function.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now