Disappearing Toggle Button macro - vba

I have simple Excel macro, for ToggleButton:
Private Sub ToggleButton1_Click()
Dim xAddress As String
xAddress = "L:R"
If ToggleButton1.Value Then
Application.ActiveSheet.Columns(xAddress).Hidden = True
Else
Application.ActiveSheet.Columns(xAddress).Hidden = False
End If
End Sub
When I upload this to OneDrive and download, macro disappear.
I have just ToggleButton definition, so it doesn't work.
How I can store this macro permanently?

Save your file as ".xlsm" or ".xlsb" file, and everything should be fine.

Related

Hide sheets VBA - Excel bug?

I am currently doing a VBA code that needs to hide some sheets when the Excel file is closed and almost everything is working fine expects when I do the following steps:
make some change/insert data in the sheets
click the save button
make another change (that I do not want to save)
click to close the file and click not to save it
The problem is that I hide the sheets but since I do not save the file (because i do not want to save the changes made at step 3) the sheets are not hidden when I reopen the file. I cannot do this with the Workbook_open method because it is not allowed (at my project).
To do this I am rewriting the beforeclose method, as follows:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim Msg As String
Dim ireply As Integer
If Not Me.Saved Then
Msg = "Do you want to save the file?"
ireply = MsgBox(Msg, vbQuestion + vbYesNoCancel)
Select Case ireply
Case vbYes
Call hidesheets
Me.Save
Case vbNo
Me.Saved = True
Application.Quit
Case vbCancel
Cancel = True
Exit Sub
End Select
Else
Call hidesheets
Me.Save
End If
End Sub
Sub hidesheets()
ThisWorkbook.Sheets("Cars").Visible = xlVeryHidden
ThisWorkbook.Sheets("Brands").Visible = xlVeryHidden
ThisWorkbook.Sheets("Models").Visible = xlVeryHidden
ThisWorkbook.Sheets("Price").Visible = xlVeryHidden
End Sub
My questions is, it is possible just to save the hidden sheets configurations/settings without saving the information/data changed/inserted by the user?
PS: when I save the file and make any change the code works fine, i.e. hides the sheets.
Thank you all in advance
Regards
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
ThisWorkbook.Sheets("Cars").Visible = xlVeryHidden
ThisWorkbook.Sheets("Brands").Visible = xlVeryHidden
ThisWorkbook.Sheets("Models").Visible = xlVeryHidden
ThisWorkbook.Sheets("Price").Visible = xlVeryHidden
End Sub
You have to do the other way around
1) Set your workbook having those four sheets as very hidden per default
set them as such and then save your workbook to have it assume its default configuration
2) When you open it you make those sheets visible
Private Sub Workbook_Open()
ThisWorkbook.Sheets("Cars").Visible = True
ThisWorkbook.Sheets("Brands").Visible = True
ThisWorkbook.Sheets("Models").Visible = True
ThisWorkbook.Sheets("Price").Visible = True
End Sub
3) When you close it, you set those sheets back invisible
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'Your code to be processed upon closing the sheet
'...
Call hidesheets '<--| hide your sheets
End Sub

Preventing Excel prompt from Word VBA

I'm working with VBA on Word and Excel. I have the Word running a userform which will automatically open an Excel file. User should fill some data in Excel file and then go back to the Word userform. When user finish filling all fields in Word userform, it will run some VBA code on Word that copy data from Excel to Word. After finished, the Excel file will be closed automatically. Therefore, I need to prevent user from closing the Excel app manually.
In order to do that, I use these code in Excel VBA in Sub Workbook_BeforeClose. If user close the Excel application window, it will show a message box that ask whether the user is still working with the Word userform. The code as follows:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
answer = MsgBox("Are you still working with Word userform?", vbYesNo)
If answer = vbYes Then
Cancel = True
MsgBox "This workbook should not be closed. It will be automatically closed when you finish working with Ms. Word Template Userform."
Else
Application.ThisWorkbook.Saved = True
End If
End Sub
In the Word VBA, I have code to close the Excel file:
Sub closeExcelApp()
If Not excelApp Is Nothing Then
excelApp.DisplayAlerts = False
excelWb.Close savechanges:=False
Set excelWb = Nothing
excelApp.Quit
End If
Set excelApp = Nothing
End Sub
This Sub will be called when the Word VBA code done copying data from Excel to Word. However, calling this Sub will cause the Workbook_BeforeClose called. Meanwhile, I don't want the Workbook_BeforeClose called when I call this closeExcelApp sub from Word VBA.
Any suggestion?
You can just disable events:
Sub closeExcelApp()
If Not excelApp Is Nothing Then
excelApp.DisplayAlerts = False
excelApp.EnableEvents = False
excelWb.Close savechanges:=False
Set excelWb = Nothing
excelApp.Quit
End If
Set excelApp = Nothing
End Sub
As explained in comments, add this line on top of the modules : Public ClosingFromWord As Boolean and set this boolean to False when you start your code execution.
As you are working between apps, the easiest way will be to write the value of the boolean in a cell in Excel from Word and read/laod this value in the Workbook_BeforeClose to avoid going through the whole code of that routine.
And modify you code to look like this :
Sub closeExcelApp()
ClosingFromWord = True
excelApp.Workbooks(1).Sheets(1).Cells(1,1) = ClosingFromWord
If Not excelApp Is Nothing Then
excelApp.DisplayAlerts = False
excelWb.Close savechanges:=False
Set excelWb = Nothing
excelApp.Quit
End If
Set excelApp = Nothing
ClosingFromWord = False
excelApp.Workbooks(1).Sheets(1).Cells(1,1) = ClosingFromWord
End Sub
So while you execute closeExcelApp, the boolean will be set to True and the Workbook_BeforeClose won't be executed in his totality as it'll be exited with If ClosingFromWord Then Exit Sub :
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ClosingFromWord = Workbooks(1).Sheets(1).Cells(1,1)
If ClosingFromWord Then Exit Sub
answer = MsgBox("Are you still working with Word userform?", vbYesNo)
If answer = vbYes Then
Cancel = True
MsgBox "This workbook should not be closed. It will be automatically closed when you finish working with Ms. Word Template Userform."
Else
Application.ThisWorkbook.Saved = True
End If
End Sub

How to disable Auto_Open after first save

When opening up a template a macro that is Auto_Open runs this code:
Sub Auto_Open()
UserForm.Show
End Sub
This then brings up a userform that says please save as and a Ok command button.
When Ok is clicked it has the this code.
Private Sub SaveAs_Click()
Dim bFileSaveAs As Boolean
bFileSaveAs = Application.Dialogs(xlDialogSaveAs).Show
If Not bFileSaveAs Then MsgBox "User cancelled", vbCritical
Unload Me
End Sub
Problem is after the Auto_Open is ran for the first SaveAs i want it to never run again. Because I want to be able to open it later with out the Userform popping up. So how do I disable the Auto_Open once its run and then save it disabled
I cant disable all macros because there are others in the workbook that still need to work.
Thanks
You have to use the Workbook.SaveAs method MSDN Found Here after you get the SaveAsFilename...
As for deleting a sub after it runs (I'd do this before saving) See here... You'll need your Auto Open Sub in a different module so you can delete the module before saving.
Private Sub SaveAs_Click()
Dim x As Object
Set x = Application.VBE.ActiveVBProject.VBComponents
x.Remove VBComponent:=x.Item("TestModule") 'Where TestModule is the module that holds the Auto Open script
Set NewBook = Workbooks.Add
Do
fName = Application.GetSaveAsFilename
Loop Until fName <> False
NewBook.SaveAs Filename:=fName
fName = False
Unload Me
End Sub
Exit auto_open if file name without specific wording.
For example: If file name is not starting from "N", auto_open will be exit.
Sub auto_open()
VBA_CODE = ActiveWorkbook.Name
If Left(VBA_CODE, 1) <> "N" Then Exit Sub

ActiveX control Blocks Me.Saved=True

Previously I have used this:
Private Sub Document_Close()
Me.Saved = True
End Sub
to disable the save prompt when exiting a Word document and changes have been made, however I have added a "Combo Box (ActiveX Control)", and now Word is prompting to save again. Is there a way around this?
I've tried writing code to just delete the Combo Box when the document closes, but the box deletes itself after being used (not my code, it just does), then when the document closes the box doesn't exist and causes an error there. I could just do an if exist/error control, but I feel like that is just getting sloppy instead of finding the root problem... can someone help?
If had the same issue, and found the solution with Bing:
http://answers.microsoft.com/en-us/office/forum/office_2007-customize/activex-control-blocks-ms-word-vba/71eca664-8e43-4e4f-84c5-59154661ee5a
The following code helped me to get around this issue:
Dim WithEvents App As Application
Private Sub App_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
'Did the user saved our file?
If Not ThisDocument.Saved Then
'Close our file?
If Doc.Name = ThisDocument.Name Then
'Cancel the dialog always!
Cancel = True
'Set the save state
ThisDocument.Saved = True
'Close the document after this event
Application.OnTime Now + TimeSerial(0, 0, 1), Me.CodeName & ".Document_AfterClose"
End If
End If
End Sub
Sub Document_AfterClose()
'Close the document without saving
ThisDocument.Close False
End Sub
Private Sub cboEquip_Change()
'Let the document know that a change is made
ThisDocument.Saved = False
End Sub
Private Sub Document_Open()
Set App = Application
End Sub

How to disable the MS Word "macro-free document" warning with code?

I have an application that dynamically insert VBA code to help building a MS word document with proper bookmarks. The VBA code doesn't need to be saved with the document itself.
When saving the document, the following warning (unfortunately I can't post an image yet) will pop up that confuses the end users of the application. Is there a way to disable this within the DocumentBeforeSave event?
**
The following cannot be saved in a macro-free document: VBA project To
save a file with these features, click No to return to the Save As
dialog, and then choose a macro-enabled file type in the File Type
drop-down. Continue saving as a macro-free document?
buttons: [Yes][No][Help]
**
One idea is to change the document's SaveFormat to an older format in order to prevent this warning from popping up. But I'm not sure if this change will affect how the document behaves going forward and if it's even possible to modify this property within the DocumentBeforeSave event (the property is a READONLY property).
Thanks in advance for any help on this topic.
The following code will open a word (assuming c:\work\test.docx exist, which can be just a blank word doc). If you hit the Save button on the word doc, the warning message will show up. BTW, I'm using Office 2010.
<TestMethod()>
Public Sub testWord()
Dim wApp As New Word.Application()
Dim myDoc As Word.Document
Dim DataCodeModule As Object = Nothing
myDoc = wApp.Documents.Open("C:\Work\test.docx")
DataCodeModule = myDoc.VBProject.VBComponents(0).CodeModule
With DataCodeModule
.InsertLines(1, "Option Explicit")
.InsertLines(2, "Sub TestCode()")
.InsertLines(3, "Selection.InsertAfter ""test""")
.InsertLines(4, "End Sub")
End With
wApp.Visible = True
myDoc.Activate()
End Sub
And once the DocumentBeforeSave is hooked up, I was hoping the following code would disable the warning. Maybe the DisplayAlerts need to be set as soon as the document is opened?
Public Sub App_DocumentBeforeSave(ByVal doc As Object, ByRef saveAsUI As Boolean, ByRef cancel As Boolean) Handles _officeHelper.DocumentBeforeSave
Dim WordApp As Object = this.WordApp()
'WordApp.DisplayAlerts = False
WordApp.DisplayAlerts = 0
End Sub
Like this?
Application.DisplayAlerts = wdAlertsNone
'~~> Your Save Code
Application.DisplayAlerts = wdAlertsAll
FOLLOWUP
You are doing it in vb.net. I don't have access to VB.net at the moment but this example below will set you on the right path
Open Word and insert a module and then paste this code
Option Explicit
Dim MyClass As New Class1
Sub Sample()
Set MyClass.App = Word.Application
End Sub
Now insert a Class Module and paste this code
Public WithEvents App As Word.Application
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, _
SaveAsUI As Boolean, Cancel As Boolean)
Application.DisplayAlerts = wdAlertsNone
ActiveDocument.Save
Application.DisplayAlerts = wdAlertsAll
End Sub
Now if you press the save button, you will notice that you won't get that alert any more. :)
Hope you can adapt it as required :)
I simply done this code . It will prompt you to save and also help you in attaching it to email.
It worked for me.
Please try. I gave a command button on top of the sheet.
Thanks
Private Sub CommandButton1_Click()
Dim whatfolder, whatfile As String
whatfolder = InputBox("Type folder name.. Don't type which drive")
whatfile = InputBox("Type file name you want to give")
ChangeFileOpenDirectory "C:\" & whatfolder
Application.DisplayAlerts = wdAlertsNone
ActiveDocument.SaveAs FileName:=whatfile & ".docx", FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:=False
Application.DisplayAlerts = wdAlertsNone
ActiveDocument.SendMail
End Sub