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

后端 未结 3 1164
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 19:50

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

相关标签:
3条回答
  • 2020-12-06 19:53

    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
    
    0 讨论(0)
  • 2020-12-06 20:01

    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 
    
    0 讨论(0)
  • 2020-12-06 20:18

    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
    
    0 讨论(0)
提交回复
热议问题