VBA Forms in custom addin - excel

I am trying to create an excel addin which has a button when clicked will display a VBA form. Its quite simple one list box and one command button.
Below is the code in Command button
Private Sub CommandButton1_Click()
ThisWorkbook.IsAddin = False
On Error GoTo ErrHandler:
KeyAcc = WorksheetFunction.VLookup(ComboBox1.Value, Sheet1.Range("A:B"), 2, False)
MsgBox KeyAcc
ThisWorkbook.IsAddin = True
Unload Me
Exit Sub
ErrHandler:
MsgBox ComboBox1.Value & " Not found in the Database"
ThisWorkbook.IsAddin = True
Unload Me
ActiveWorkbook.Save = False
End Sub
Code in form load
Private Sub UserForm_Activate()
Application.ScreenUpdating = False
Dim cCount As Integer
ThisWorkbook.IsAddin = False
ThisWorkbook.Sheets("Sheet1").Select
For cCount = 1 To 320
UserForm1.ComboBox1.AddItem Range("A" & cCount).Value
Next
ThisWorkbook.IsAddin = True
ComboBox1.SetFocus
End Sub
The problem i face is whenever the user activates this button on the first book ie, after opening a new excel and performs the operation it works, once done when i try to close the blank workbook it asks do you want to Save your changes to the Addin
Is there any way to avoid this?

You don't need all that work just to load your combobox:
Private Sub UserForm_Activate()
Me.ComboBox1.List = ThisWorkbook.Sheets("Sheet1").Range("A1:A320").Value
ComboBox1.SetFocus
End Sub

Related

Entire Application Disappears (runs in background) instead of opening worksheet "Sheet1" in VBA

I have 2 Userforms. In userform1, sheet to open is selected together with some textbox. In Userform2, there are additional option boxes and a command button to unload Userform2 and Activate worksheet 1 but it won't load...i used to be able to run it until i added a code to prompt user to complete fields..not sure what is wrong with my code that it won't proceed opeining the worksheet anymore
Userform1 Code:
Private Sub CommandButton1_Click()
If TextBox1.Value = "" Then
MsgBox "Pls. enter data"
Cancel = True
Exit Sub
End If
If Sheet1.Value = True Then
Unload UserForm1
UserForm2.Show
Userform2 Code:
*'to prompt user to complete fields*
Private Sub CommandButton1_Click()
If OptionBox1.Value = False And OptionBox2.Value = False Then
MsgBox "Pls. select option"
Cancel = True
Exit Sub
End If
*'to open worksheet "Sheet1"*
If UserForm1.Sheet1.Value = True Then
Worksheets("Sheet1").Activate
Application.Visible = True
Unload UserForm2
End If
End Sub
Once you unload UseForm1 it's no longer accessible from UserForm2 - you should instead Hide UserForm1 until you're done with it, and only then Unload it.

Why does my sub not work when it runs fine in immediate window excel vba

I've been trying to get the typical hide sheets/unhide sheets code to work for encouraging Macro enabling. Since I lock down saving, I needed to do it slightly differently than putting it in the Workbook_BeforeClose Sub as usually is done.
But...my hide sub
Sub HideSheets()
'Error Handling when workbook is unprotected.
On Error GoTo EH
'Unprotect the workbook to allow conditional formatting changes.
ThisWorkbook.Sheets("Field Service Report").Unprotect Password:="x"
ThisWorkbook.Sheets("Prompt").Unprotect Password:="x"
'Main Sub Code
Application.EnableCancelKey = xlDisabled
Sheets("Prompt").Visible = xlSheetVisible
Sheets("Field Service Report").Visible = xlSheetVeryHidden
Application.EnableCancelKey = xlInterrupt
'Reprotect worksheet before ending sub.
ThisWorkbook.Sheets("Field Service Report").Protect Password:="x", UserInterfaceOnly:=True
ThisWorkbook.Sheets("Prompt").Protect Password:="x"
Exit Sub
EH:
Call EH
Resume Next
End Sub
and my unhide sub
Sub UnhideSheets()
'Error Handling
On Error GoTo EH
'Unprotect the workbook to allow conditional formatting changes.
ThisWorkbook.Sheets("Field Service Report").Unprotect Password:="x"
ThisWorkbook.Sheets("Prompt").Unprotect Password:="x"
'Main Sub Code
Application.EnableCancelKey = xlDisabled
Sheets("Field Service Report").Visible = xlSheetVisible
Sheets("Prompt").Visible = xlSheetVeryHidden
Application.EnableCancelKey = xlInterrupt
'Reprotect worksheet before ending sub.
ThisWorkbook.Sheets("Field Service Report").Protect Password:="x", UserInterfaceOnly:=True
ThisWorkbook.Sheets("Prompt").Protect Password:="x"
Exit Sub
EH:
Call EH
Resume Next
End Sub
....works fine when called form the immediate window. Sheets hide and unhide appropriately.
But, when I step through the sub it doesn't actually do anything. The idea is to set the sheets to the "prompt" sheet before saving, save, then revert to usable after saving. But I can't even see if that code is working correctly (it appears to) because stepping through the actual hide/unhide subs doesn't do anything.
Edit: No errors, just doesn't change any settings to hide or unhide sheets.
Thoughts?
Edit: So given the comments below, my subs work when run from the immediate window and when stepped through via debugger. They hide and unhide the worksheets appropriately. So, the only thing that can be wrong is the code that calls these subs. So, here are two more subs. One is the button code for a save button, and the other is the Workbook_BeforeSave Sub.
Sub Save_Form()
'Error Handling ...
On Error GoTo EH
'Unprotect the workbook ...
ThisWorkbook.Sheets("Field Service Report").Unprotect Password:="x"
'Variable to disable any other save but this button.
Module1.SaveChk = 1
'Code to automatically save a copy ...
Module1.UserPath = Environ("USERPROFILE")
Module1.Path = UserPath & "\Desktop\"
If Module1.EditChk = "Y" Then
Module1.SaveName = "FSR Master"
Else
Module1.SaveName = Range("AF6").Value
End If
ThisWorkbook.SaveAs _
Filename:=Path & SaveName & ".xlsm", _
FileFormat:=52
If Module1.SaveError <> 1 Then
'User Display of Save Success
MsgBox "Filename = " & SaveName & vbNewLine _
& "File is saved to your desktop."
Else
Module1.SaveError = 0
End If
'Reset SaveChk variable
Module1.SaveChk = 0
'Reprotect Worksheet
ThisWorkbook.Sheets("Field Service Report").Protect Password:="x", UserInterfaceOnly:=True
Exit Sub
EH:
Call ErHa
Resume Next
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'Error Handling ...
On Error GoTo EH
'Save Initiation Check
If Module1.SaveChk <> 1 Then
Cancel = True
MsgBox "Please Use Form Save Button", vbOKCancel + vbExclamation, "SAVE CANCELLED"
Exit Sub
End If
If Module1.EditChk <> "Y" Then 'Skips the whole block if EditChk = Y
'Create the final range of cells for checking
Set Module1.Required = Application.Union(Module1.Fixed, Module1.Drive, Module1.Stage)
'Check if all required cells are filled in
If WorksheetFunction.CountA(Module1.Required) < Module1.Required.Count Then
Cancel = True
MsgBox "Please Completed Shaded Cells!", vbOK + vbExclamation, "SAVE CANCELLED"
Module1.SaveError = 1
Else
'Set the report date before saving
Application.EnableEvents = False
Range("AE59") = Format(Now(), "mm-dd-yyyy hh:mm:ss AM/PM")
Application.EnableEvents = True
End If
End If
'Renable Macro Splash Screen Before Save
Call HideSheets
Exit Sub
EH:
Call ErHa
Resume Next
End Sub

Determine if the protected view options are active within the document

At the time of opening a document, it indicates to view it I must enable editing of the protected view.
I want at the time it is detected, to close the document until deleting that configuration of Excel.
Is there any small VBA function that does this procedure?
error 91 occurred at variable object runtime with block not set
If Application.ProtectedViewWindows.Count > 0 Then
ActiveWorkbook.Close savechanges:=False
Application.Quit
Else
End If
The entire ActiveWorbook code
Private Sub Workbook_Open()
Dim hoja As Worksheet
For Each hoja In ThisWorkbook.Worksheets
hoja.Visible = xlSheetVisible
Next hoja
If Application.ProtectedViewWindows.Count > 0 Then
ActiveWorkbook.Close savechanges:=False
Application.Quit
Else
End If
If Not VBATrusted() Then
Application.Visible = False
MsgBox "Aviso. Ya no puedes usar este archivo. Comunícate con el desarrollador Arq. Luis Eduardo Ramírez Aguayo entremuros.masterplan#hotmail.com Cel. +(52) 415.151.102"
ActiveWorkbook.Close savechanges:=False
Application.Quit
End If
Sheets("Hoja1").Visible = xlVeryHidden
'----------------------------------------------------------------'
Application.Visible = False
UserForm1.Show
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim hoja As Worksheet
Sheets("Hoja1").Visible = xlSheetVisible
For Each hoja In ThisWorkbook.Worksheets
If hoja.Name <> "Hoja1" Then
hoja.Visible = xlSheetVeryHidden
End If
Next hoja
'----------------------------------------------------------------'
Sheets("HojaEscondida").Range("A4") = "admin"
Sheets("HojaEscondida").Range("A4") = "admin"
Application.DisplayAlerts = False
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If SaveAsUI Then
MsgBox "NO SE PUEDE GUARDAR COMO." & Chr(10) _
& "Guarde el original, usando el icono guardar," & Chr(10) _
& "o simplemente use la x de cerrar, y se guardará" & Chr(10) _
& "automáticamente en el lugar correcto", vbCritical
Cancel = True
End If
End Sub
Function VBATrusted() As Boolean
On Error Resume Next
VBATrusted = (Application.VBE.VBProjects.Count) > 0
End Function
Try this one.
Click File > Options.
Click Trust Center > Trust Center Settings > Protected View.
Uncheck Enable Protected View for files originating from the internet.
Hope it helps
Protected View is a security feature that disables macros and editing of the file. If you could run VBA code in the protected view this would be a securtity hole. Therefore you cannot run any code in protected view.
As a workaround you can add a worksheet ProtectionInfo and write some warning message on in like "This workbook needs to be opened with macros enabled and without protected view!"
Then you write a code in your Workbook_Open which hides the worksheet ProtectionInfo if the workbook opens. That means if macros are enabled and the user is not in protected view he will not see the warning worksheet. But if macros are disabled or in protected view, the user will see the warning.
Make sure to make the worksheet ProtectionInfo visible on Workbook_BeforeClose so it is shown again next time anyone opens it with macros disabled. Additionally you might want to hide all other worksheet so ProtectionInfo is the only worksheet that is shown when macros are disabled.
As #Pᴇʜ said, you can only do a workaround by hiding all Worksheets except one where it says you have to disable protected view and unhide the worksheets when macros are enabled. But you should do that at Workbook_BeforeSave because some people save it in between but don't save it in the end and then the worksheets wouldn't be hidden then next time it's opened.
Since I already made that for myself for when macros are disabled with notification, I can share it here.
The following code will hide all worksheets except "No Macros" where I have a message shown how to enable macros.
Notice that I added a Variable LastSheet so when someone saves the file that it knows where to jump back to after it has unhidden all worksheets again
Dim LastSheet As String
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Unhide_Worksheets
ThisWorkbook.Saved = True
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
LastSheet = ThisWorkbook.ActiveSheet.Name
Hide_Worksheets
End Sub
Private Sub Workbook_Open()
Unhide_Worksheets
End Sub
Private Sub Hide_Worksheets()
'Application.ScreenUpdating = False
ThisWorkbook.Worksheets("No Macros").Visible = xlSheetVisible
ThisWorkbook.Worksheets("No Macros").Activate
On Error Resume Next
For Each Worksheet In ThisWorkbook.Worksheets
If Worksheet.Name <> "No Macros" Then
Worksheet.Visible = xlSheetVeryHidden
End If
Next Worksheet
On Error GoTo 0
'Application.ScreenUpdating = True
End Sub
Private Sub Unhide_Worksheets()
'Application.ScreenUpdating = False
On Error Resume Next
For Each Worksheet In ThisWorkbook.Worksheets
Worksheet.Visible = xlSheetVisible
Next Worksheet
On Error GoTo 0
If LastSheet <> vbNullString Then
ThisWorkbook.Worksheets(LastSheet).Activate
End If
ThisWorkbook.Worksheets("No Macros").Visible = xlSheetHidden
'Application.ScreenUpdating = True
End Sub

Cannot execute deletion if UserForm activated end of code

Edit: I revised the userform2 particular code with whole code
I have 2 userforms and userform2 code defined below. My problem is the sheet selected from userform2 combobox (populated from sheet names) to be deleted keep activated if the code eventually shows userform1. But makro works well and deletion becomes successful if I remove the line "UserForm1.Show". How can I delete selected sheet all and show userform1 after a successful execution? Thanks in advance for your help.
Userform2 CODE
Private Sub ToggleButton1_Click()
Dim i As Integer
i = ActiveWorkbook.Worksheets.Count
Application.DisplayAlerts = False
If UserForm2.ComboBox1.Value = "SILINECEK CARIYI SEÇIN" Then
MsgBox "CARI SEÇMEDINIZ"
Unload UserForm2
Application.Visible = True
Exit Sub
End If
If ToggleButton1.Value = True And i < 5 Then
ActiveWorkbook.Unprotect
Sheets("MASTER CARI").Visible = True
Worksheets(UserForm2.ComboBox1.Text).Delete
Unload UserForm2
Application.Visible = False
UserForm1.Show
ActiveWorkbook.Protect
Exit Sub
Else
ActiveWorkbook.Unprotect
Worksheets(UserForm2.ComboBox1.Value).Delete
Unload UserForm2
Application.Visible = True
End If
ActiveWorkbook.Protect
Application.DisplayAlerts = True
End Sub

Excel form listbox issue when using locked property

I'm having an issue with the way a listbox behaves on an Excel form. Steps to reproduce the issue:
Create a user form with one listbox control
Use following code with this user form:
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.ListBox1.Locked = True
Me.ListBox1.Locked = False
End Sub
Private Sub UserForm_Initialize()
Dim i As Integer
For i = 1 To 10
Me.ListBox1.AddItem i
Next i
End Sub
When the form is first shown, I am able to navigate the list box normally, using arrow keys and page keys. However, after the double-click event is triggered, all keyboard navigation has no effect, including tabbing to other controls (if they're on the form). Clicking on the listbox does seem to work, and the focus outline is shown correctly, but there's something wrong with the way the focus is handled after the listbox is locked and then unlocked. What is going on?
Using Office 2013 32-bit edition.
I managed to replicate this issue, and setting the focus somewhere else before locking and unlocking the listbox worked for me:
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.TextBox1.SetFocus 'or some other control.
Me.ListBox1.Locked = True
Me.ListBox1.Locked = False
Me.ListBox1.SetFocus
End Sub
2 solutions I tested that allows you to use Arrow Keys to navigate.
Given that there isn't a single click event handler, try call the Single Click Event after the DblClick (works all the time):
Private Sub ListBox1_Click()
Debug.Print "ListBox1_Click()"
End Sub
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "ListBox1_DblClick()"
With Me.ListBox1
.Locked = True
.Locked = False
End With
ListBox1_Click
End Sub
Private Sub UserForm_Initialize()
Dim i As Integer
For i = 1 To 10
Me.ListBox1.AddItem i
Next i
End Sub
Setting the Cancel = False at the end of DblClick. (Sometimes does not work!)
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "ListBox1_DblClick()"
With Me.ListBox1
.Locked = True
.Locked = False
End With
Cancel = False
End Sub
Private Sub UserForm_Initialize()
Dim i As Integer
For i = 1 To 10
Me.ListBox1.AddItem i
Next i
End Sub
Changing the zoom in the sheet that has the listbox worked for me.
Private Sub Worksheet_Activate()
Dim temp As Double
Application.ScreenUpdating = False
'Change worksheet zoom setting for the active window
temp = ActiveWindow.Zoom
ActiveWindow.Zoom = temp + 10
ActiveWindow.Zoom = temp
Application.ScreenUpdating = True
End Sub

Resources