How to Open only UserForm of an excel macro from batch file

泪湿孤枕 提交于 2020-01-19 06:06:06

问题


I'm trying to open the UserForm1 of an excel macro through batch file. I'm able to open that but excel is also getting opened along with that. I want only UserForm1 to be opened not the excel. Below is my approach :

I have written a macros to open the UserForm1

Sub open_form()
   UserForm1.Show
End Sub

In batch File:

@echo off
cd "c:\Test\"
openFormTest.xlsm

By the above approach, When I'm running the batch file both UserForm1 and excel are getting open, but I want to open only UserForm1. Kindly help me out


回答1:


You need to show the UserForm in modeless mode and then hide the application.

try this

Sub open_form()
    Application.Visible = False
    UserForm1.Show vbModeless
End Sub

and either in a button you need to set it back to true or you can use the UserForm_QueryClose event

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Application.Visible = True
    ThisWorkbook.Close SaveChanges:=False
End Sub



回答2:


There are several reasons (such as unhandled exceptions crashing your code before Application.Visible is reset to True) that it is not a good idea to do this but I'll assume you have considered these:

Private Sub UserForm_Initialize() 
    Application.Visible = False 
End Sub 

Private Sub UserForm_Terminate() 
    Application.Visible = True 
End Sub 

Private Sub Workbook_Open() 
    UserForm1.Show vbModeless
End Sub 



回答3:


In case someone wants to run a userform "alike" a stand alone application:

Issues I was facing:

  1. I did not want to use the Workbook_Open Event as the excel is locked in read only.
  2. The batch command is limited that the fact that (to my knowledge) it cannot call the macro.

I first wrote a macro to launch my userform while hiding the application (based on your comments above):

Sub open_form()
 Application.Visible = False
 frmAddClient.Show vbModeless
End Sub

I then created a vbs to launch this macro (doing it with a relative path has been tricky):

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"

And I finally did a batch file to execute the VBS...

@echo off
pushd %~dp0
cscript Add_Client.vbs

Note that I have also included the "Set back to visible" in my Userform_QueryClose:

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    ThisWorkbook.Close SaveChanges:=True
    Application.Visible = True
    Application.Quit
End Sub


来源:https://stackoverflow.com/questions/20603599/how-to-open-only-userform-of-an-excel-macro-from-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!