I'm a VERY new learner to VBA trying to decypher functions and build an interactive file. With help from one user here (who will certainly know who he is ;)), I could learn quite a few things.
Now I'm stuck at one ridiculous piece of code : I want to 1/unhide a sheet, 2/go to that sheet and 3/re-hide the sheet when the user selects the "back to the start page-button".
So I made this code :
Sub FRtoEN()
'
' FRtoEN Macro
' Emmène au Glossaire FR ==> EN
'
Sheets("synthèse_FR&EN").Visible = True
Sheets("Synthèse_FR&EN").Select
End Sub
and it works well. But I cannot find out how to tell excel in VBA-language that I want it to re-hide the tab once the user is done and clicks the exit button.
Could you help me?
Ferndiando's answer is brilliant when you want to have one button where you first show the hidden sheet and next time you click on the same button it hide the same sheet.
Making one button to show a sheet and another button to hide the same sheet, do the following;
In the first button you will make the code visible:
Sub FRtoEN()
'
' FRtoEN Macro
' Emmène au Glossaire FR ==> EN
'
Sheets("synthèse_FR&EN").Visible = True
Sheets("Synthèse_FR&EN").Activate
End Sub
In the second button that which will take the user back to the "Main Page" you can add this code:
Sub StartPage()
Sheets("Start Page").Activate 'First go to Start page
Sheets("synthèse_FR&EN").Visible = False 'Then hide the sheet they currently visited, that makes the experience a little bit more "working in background"
End Sub
If I assume you use this "back to the start page-button" for several sheets, you could hide other sheets too every time someone goes to start page.
Sub StartPage()
Sheets("Start Page").Activate 'First go to Start page
Sheets("synthèse_FR&EN").Visible = False
Sheets("synthèse_FR&DE").Visible = False 'Example 1 - No matter which sheet you visit, it will hide this sheets.
Sheets("synthèse_FR&SP").Visible = False 'Example 2 - No matter which sheet you visit, it will hide this sheets.
End Sub
If you want the code to perform things on hidden sheets, while they still are hidden for the user (for example background filtering/calculations/copy data etc..) this will give the user a smooth experience:
Sub StartPage()
Application.ScreenUpdating = False 'Turn of all visual updates the macro does. Macro works in background without showing every step visually in Excel.
Sheets("synthèse_FR&EN").Visible = True 'Unhide the sheet you want to work at.
'Do some filtering stuff // copy stuff
Sheets("synthèse_FR&EN").Visible = False 'Re-hide the sheet again.
Application.ScreenUpdating = False 'Turn ON all visual updates the macro does. Macro now works and shows every step visually in Excel.
End Sub
:)
If i understood your question you can use this code:
Sub myButton()
'Hide and Show Sheet2 with same button
' you can change the sheet name as you prefer
If (Sheets("Sheet2").Visible) Then ' control if the sheet is visible
Sheets("Sheet2").Visible = False ' hide sheet2 because before was showed
Sheets("Sheet1").Select ' select sheet1
Else
Sheets("Sheet2").Visible = True ' show sheet2 because before was hidden
Sheets("Sheet2").Select 'select sheet2
End If
End Sub
I hope this help you.
Related
I am developing an electronic audit sheet for work, where the desire is to generate a new work sheet each day, copied from a blank master sheet. This part is easy, I have a simple macro attached to a button that generates a copy of my master sheet, places it last in the tab, and automatically names it the current day's date.
Sub NewDay()
Sheets("Master").Copy After:=Worksheets(Worksheets.Count)
NewPageName = Format(Date, "dd-mm-yyyy")
ActiveSheet.Name = NewPageName
End Sub
What I would now like to do is to give the ability to create a new sheet from a selection of 'master' sheets, while retaining the date-as-sheet-name part.
Ideally, the user experience would be to select from a drop down menu the sheet, and click a button to create the new sheet, or to click the button, be presented with the list of options to select, and then generate.
I am relatively inexperienced at VBA, and this is beginning to go out of what little realm of mastery I have. Any and all help would be greatly appreciated.
For selecting items from a list in a User form, I strongly recommend ComboBox. In Project Explorer, insert a userform, and add a ComboBox and a Button. To create the list for the user to select from. We need to have our macro do ComboBox.Add(SheetName,Index) for each of the Master Sheets. To keep track of everything, it's best to have them declared in an array.
We then pop-up the form for the user to interact with using UserForm.Show. Once the user has made their selection, the select button does UserForm.Hide to close the form.
Since we created the combobox list from an array, the list index of the selected item is equivalent to the array index of the sheet we want to copy.
Sub Start()
Dim MasterSheets() As Variant, ShtSelect As Integer
MasterSheets = Array(Sheet1, Sheet2, Sheet3, Sheet4)
'This is your list of Master Sheets.
'Change Sheet1 and Sheet2 to Sheets("Master1") and Sheets("Master2")
With UserForm1
.ComboBox1.Clear
For i = LBound(MasterSheets) To UBound(MasterSheets)
.ComboBox1.AddItem MasterSheets(i).Name, i
Next i
.Show
ShtSelect = .ComboBox1.ListIndex
'This is how to get the user selected item from the ComboBox
End With
'The Selected Sheet is referenced by MasterSheets(ShtSelect)
'Your code from before
MasterSheets(ShtSelect).Copy After:=Worksheets(Worksheets.Count)
NewPageName = Format(Date, "dd-mm-yyyy")
ActiveSheet.Name = NewPageName
End Sub
These are the only lines inside UserForm1
Private Sub CommandButton1_Click()
If UserForm1.ComboBox1.ListIndex <> -1 Then Me.Hide
'ListIndex = -1 means that the user has not yet selected anything.
End Sub
You may also want to check to see if a sheet with that name already exists before attempting to create it. Otherwise you may run into errors if someone runs the macro twice in one day.
I would suggest something like:
NewPageName = Format(Date, "dd-mm-yyyy")
If Sheets(NewPageName) Is Nothing Then 'Only copy if it doesn't already exist
MasterSheets(ShtSelect).Copy After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = NewPageName
End If
I’m very new to Excel VBA but managed to create three buttons in a staff timesheet. All buttons work as needed, however, one particular button is causing random issues – about 90% of the time it works, but from time to time it will crash Excel or give an error such as runtime error '-2147417848 (800 10 108)': Automation error The object invoked has disconnected from its clients. Other times it’s a similar message, saying Method ‘Insert’ of object ‘Range’ failed.
It’s happening in different versions of Excel on different computers. The task is not complex but I’m stumbling with my VBA knowledge.
The user clicks the button to set up each formatted row in the sheet called “Timesheet”, i.e. clicking the button in “Timesheet” copies a row from sheet4 (formatted and containing formulae) and inserts it into the “Timesheet” above the button.
I’d be very grateful if someone could suggest alternative code that won’t crash Excel - many thanks in advance!
Sub NewSlot()
' NewSlot Macro used in Timesheet
'
'turn protection off
Worksheets("Sheet4").Unprotect Password:="mypasswd"
Worksheets("Timesheet").Unprotect Password:=" mypasswd "
' select row 8 in sheet4
Sheets("Sheet4").Select
Rows("8").Select
Selection.Copy
' go back to timesheet
Sheets("Timesheet").Select
' insert copied row
Dim r As Range
Set r = ActiveSheet.Buttons(Application.Caller).TopLeftCell
Range(Cells(r.Row, r.Column), Cells(r.Row, r.Column)).Offset(0, 0).Select
Selection.Insert shift:=xlDown
Application.CutCopyMode = False
'turn protection on
Worksheets("Sheet4").Protect Password:=" mypasswd "
Worksheets("Timesheet").Protect Password:=" mypasswd"
End Sub
If you are going to use VBA to repeatedly modify a protected worksheet, unprotect it then protect it once with UserInterfaceOnly:=True.
sub protectOnce()
worksheets("Timesheet").unprotect password:="mypasswd"
worksheets("sheet4").unprotect password:="mypasswd"
worksheets("Timesheet").protect password:="mypasswd", UserInterfaceOnly:=True
worksheets("sheet4").protect password:="mypasswd", UserInterfaceOnly:=True
end sub
After that has been done once you will not have to unprotect to modify with VBA. If you have to unprotect it for another reason, reprotect it with with UserInterfaceOnly:=True.
This cuts your NewSlot code down significantly. It is considered 'best practise' to avoid using Select and Activate, particularly across worksheets.
Sub NewSlot()
' select row 8 in sheet4
workSheets("Sheet4").Rows("8").Copy
' go back to timesheet
with workSheets("Timesheet")
' insert copied row
Dim r As Range
Set r = .Buttons(Application.Caller).TopLeftCell
.Cells(r.Row, "A").entirerow.Insert shift:=xlDown
end with
End Sub
Im trying to make a macro for userform to input data in to hiden sheet. I have tryied application screening then visible the sheet and then input the data in a specific cell but ints not working like that.
Anyone know how it works?
You don't need to make a sheet visible to populate it.
For example, create a new workbook and make sure there is a sheet in there called Sheet2
Hide Sheet2
Put this into the debug window (ctrl-g) in the VB Editor
Sheets("Sheet2").range("A1").Formula = "Text in a hidden sheet"
press enter
Unhide Sheet2 and look at cell A1
Looks like thats not the only problem i have got. I will try to explain it. When a press a button a userform pop up and there is a text box in it. You write a name in the box, click a button and the name appears is a cell in one of the sheets that is hidden. That we already did.
Then i want to move to another sub which is located in one of the sheets. The other sub is for printing out a hidden sheet.
I have an Option Explicit there and
A sub called PrintFile.
Application.ScreenUpdating = False
With Sheets("Opis")
.Visible = True
.PrintOut
.Visible = False
End With
Application.ScreenUpdating = True
The problem is that it's giving me an error and i can't switch to the other sub.
Where im doing it wrong?
Forgive my ignorance (newby and little knowledge of VBA)...
I have developed some macros that are attached to buttons, and working in one worksheet in a workbook. The macros perform various jobs on a calendar. There is one calendar for each of 10 bedrooms in the wing of a hospital.
I now want to make identical worksheets with the same buttons and macros for each bedroom i.e. 10 worksheets.
But try as I might I cant get the macros to work in the other worksheets.
The macros are in the VBA code editor for the first worksheet (Bed1). I have copied the code into the "This Workbook" page within the VBA editor - but that had no effect, other than to stop them working at all.
This is a typical macro:
'============================================
Private Sub Prevw1_Click()
'============================================
' DAILY PATIENT TIMETABLE
' PRINT PREVIEW
'============================================
ActiveSheet.Select
ActiveSheet.AutoFilterMode = False
Range("_Daily").Select
ActiveSheet.PageSetup.PrintArea = "_Daily"
'
Call page_SetUp
'
' Variations for page setup
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(1.5)
.RightMargin = Application.InchesToPoints(0.9)
.Zoom = 75
End With
ActiveSheet.PrintPreview
ActiveSheet.PageSetup.PrintArea = ""
Range("H126, H126").Select
End Sub
Q. What have I done wrong that makes this only work in the Bed1 worksheet where it was developed first?
Kind regards
Russ
Take the code out of the ThisWorkbook module and put it in a normal code module. In Design Mode, in the Excel window (not VBE), right-click the button and do Assign Macro, then choose the macro "Prevw1_Click". That should work. You'll have to assign the macro to each button, or you could simply copy/paste the button to the other sheets.
If your button is an ActiveX Control, then I think you may need to have the subroutine for each button in the worksheet where the button resides. So, each worksheet may have an activeX command button called "CommandButton1", then each Worksheet code module should have a subroutine like:
Sub CommandButton1_Click()
Call ClickTheButton
End Sub
You will basically put all of this same code in each of the 10 worksheet code modules. Then, rename your routine in the ordinary code module, like:
Private Sub ClickTheButton()
'============================================
' DAILY PATIENT TIMETABLE
' PRINT PREVIEW
'============================================
ActiveSheet.Select
ActiveSheet.AutoFilterMode = False
Range("_Daily").Select
ActiveSheet.PageSetup.PrintArea = "_Daily"
'
Call page_SetUp
'
' Variations for page setup
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(1.5)
.RightMargin = Application.InchesToPoints(0.9)
.Zoom = 75
End With
ActiveSheet.PrintPreview
ActiveSheet.PageSetup.PrintArea = ""
Range("H126, H126").Select
End Sub
The reason I would do this, instead of copying the existing macro to each of 10 worksheets is simple: If you ever need to modify your subroutine, you only need to modify it in one place. Likewise, if you add a new worksheet(s) you need only copy 3 lines of code instead of 20. It's just easier to maintain this way, since each sheet's button is calling the same code, each sheet's button should just have a simple sub that calls the "main" procedure.
I am trying to freeze panes using code in excel. i have seen several examples on how to do it with the activewindow, im trying to
sepcify it from a button on a different sheet.
I have 2 sheets, "Time" and "Time_and_Cost", i have a button on the "Time" sheet which i want to freeze the top row of
"Time_and_cost".
I have this code currently for freezing panes of the active window.
Rows("1:1").Select
ActiveWindow.FreezePanes = True
However, how can i adapt this to specify the worksheet, i assume i have to select the worksheet to freeze, freeze it, then
select previous worksheet? im having trouble find the exact code to use.
Thanks in advance
How about something like this:
Public Sub FreezePane()
Dim shName As String
shName = ActiveWindow.ActiveSheet.Name
ActiveWorkbook.Worksheets("Time_and_Cost").Activate
Range("A2").Activate
ActiveWindow.FreezePanes = True
ActiveWorkbook.Worksheets(shName).Activate
End Sub
Note that I'm activating A2 on "Time_and_Cost" prior to freezing the panes so that the top row will be frozen.
You can try the below.
Sub FreezePanes()
Worksheets("Time_And_Cost").Activate
Rows("2:2").Select
ActiveWindow.FreezePanes = True
End Sub