Show/hide number of rows based on "n" - excel

I am trying to show/hide a number of rows based on "n".
The rows I'm trying to show or hide span from rows 21 to 70. My input cell for "n" is B14.
Say if B14 is 2 then I only want rows 21 and 22 to be visible (23 to 70 hidden). If B14 is 48 then rows 21 to 68 visible and so forth.
Can someone help me with the macro required to achieve this?

Try this code, please. It will automatically hide the rows according to the changed value in "B14". Copy the code in the sheet module. In order to do that, select the sheet to be processed, right click on its page and choose "View Code". Copy the code there, go back in the sheet, start playing with values in "B14" and send some feedback about its behavior:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B14")) Is Nothing Then
Dim lastRow As Long, visRows As Long
If IsNumeric(Range("B14").Value) Then
visRows = Range("B14").Value
Else
MsgBox "In range ""B14"" must be a number!": Exit Sub
End If
If visRows = 50 Then
lastRow = 69
Else
lastRow = 70
End If
Range("A:A").EntireRow.Hidden = False 'make all rows visible
Range(Range("A21").Offset(visRows), Range("A" & lastRow)).EntireRow.Hidden = True
End If
End Sub

The following VBA code should work
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngWatched As Range, n As Long
Set rngWatched = Me.Range("B14")
If Not Intersect(Target, rngWatched) Is Nothing Then
With Me.Range("A21:A70")
.EntireRow.Hidden = True
n = rngWatched.Value
If n > 0 Then
.Cells(1, 1).Resize(n, 1).EntireRow.Hidden = False
End If
End With
End If
End Sub
To use the code, please follow these steps:
Press Alt+F11. This will take you to the VBA editor window
On the left hand side you will see a project explorer
Expand VBAProject(YOUR_EXCEL_FILENAME)
Expand Microsoft Excel Objects
Double-click on the relevant sheet. This will open the sheet class page
Paste the code here
Close the VBA editor window and go back to excel
Make sure the file is then saved as Excel Macro-Enabled workbook (*.xlsm)

Related

Ignite VBA macro in excel, if cell value is changed without code crash?

An excel spreadsheet that is as an input-form for users. Based on their input and selections via dropdown my intention is to guide them through the form by hiding & unhiding rows with input fields, presenting the users with the relevant questions.
On each row I have created an IF-formula that creates a 1 or 0 based on previous provided input 1 -> unhide the row , 0 -> hide the row.
So I'm looking for a macro that runs with every sheet calculation and hides or unhides the next rows as needed.
These formulas are in range I3:I70 on top of that I created a summary field in I2 =sum(I3:I70) so i thought I can either check changes in the range I3:I70 or changes on cell I2 to trigger the macro. [Neither solution fixed my problem]
I've tried several code examples discribed on the forums and I've tested the macros that checks for change in the range or the cell individually. As long as I call a test macro with a MsgBox it works fine. Also the macro that hides or unhides runs fine when I call it manually.
My problem: When I let the 'auto'-macro call the 'hide'-macro, Excel simply crashes; no warnings, nothing --> just crash.
My code:
Private Sub Worksheet_Calculate()
Dim Xrg As Range
Set Xrg = Range("H3:H70")
If Not Intersect(Xrg, Range("H3:H70")) Is Nothing Then
Macro1
End If
End Sub
Sub Sample()
MsgBox "Yes"
End Sub
Sub Macro1()
Dim cell As Range
For Each cell In Range("H3:H70")
If Not IsEmpty(cell) Then
If cell.Value = 0 Then
cell.EntireRow.Hidden = True
End If
If cell.Value = 1 Then
cell.EntireRow.Hidden = False
End If
End If
Next
End Sub
Thanks for any suggestions and tips in advance.

Macro to autofill a cell based on a value in a different sheet

I'm having a hard time trying to find a macro for the following use:
Taking in consideration this example:
Consider that i have in the "sheet 1" the table with the columns Country and Food with its values.
In the sheet 2, i have two columns named Country#1 and Food#1. The macro i want, needs to autofill the Food#1 cell that is associated with the right text in Country#1 cell, via the drop down list.
Example: When i select "Madrid" in Country#1, it needs to autofill the Food#1 with the text "Tapas and tortillas".
I'm sorry if this is a re-post question, but i didn't saw anything close as this :|
Best regards,
Luís
You need a Sheet Change Event like below...
The following code assumes that you have a list of Countries and their food in column A and B respectively on Sheet1 and the country dropdown list is in column A on Sheet2.
Right click the Sheet2 Tab --> View code --> Past the following code into the opened code window.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
Dim wsSource As Worksheet
Dim r As Long
Set wsSource = Sheets("Sheet1") 'Source sheet which contains a table of countries and their food
If Target.Column = 1 And Target.Row > 1 Then
If Application.CountIf(wsSource.Columns(1), Target.Value) > 0 Then
Application.EnableEvents = False
r = Application.Match(Target.Value, wsSource.Columns(1), 0)
Target.Offset(0, 1) = wsSource.Cells(r, 2)
Application.EnableEvents = True
End If
End If
End Sub

View and hide columns in excel using vba

I have a worksheet with values in columns B:G. In the same sheet in cell A1 I have made a drop down list using data validation with values like A, B and C.
What I require is when I select cell value A then columns B:C need to be visible and the other columns should be hidden from D:G. In the same way if I select B from the list I need to view columns D:E and B:C and F:G should be hidden.
Could you please help me on this.
Note: I don't have good knowledge in VBA.
Try this:
Open the VBA editor (ALT + F11)
Double click Sheet1
Select Worksheet in the top left drop down and Change in the top right hand drop down
Paste this code
NB- this assumes data validation is in cell A1
Private Sub Worksheet_Change(ByVal Target As Range)
Dim allColumns As Range
Set allColumns = Columns("B:G")
allColumns.Hidden = True
If Not Intersect(Target, Range("A1")) Is Nothing Then
If Target.Value = "A" Then
Columns("B:C").Hidden = False
ElseIf Target.Value = "B" Then
Columns("D:E").Hidden = False
ElseIf Target.Value = "C" Then
//Add more logic here
End If
End If
End Sub
Go to view --> macros.
Hit the dropdown and do "record new macro".
Right click on a column header and do hide column.
Then do unhide column.
Do Macros->stop recording.
Macros-->View macros
Click edit.
you get the following code:
Columns("C:C").Select
Selection.EntireColumn.Hidden = True
Selection.EntireColumn.Hidden = False
Now you know how to hide and show columns. First you select the column then your set Hidden = true or false.
Google: excel macro when cell value changes
Click the first link: http://support.microsoft.com/kb/213612
Take the code from that link and read the comments:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A1:C10")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
MsgBox "Cell " & Target.Address & " has changed."
End If
End Sub
Make sure you read the link very closely. And follow the instructions. I find I sometimes rush and miss important details
Let me know if this is enough or you need more help.
It's been a long time, but it may still be useful to someone.
Userform to hide-unhide worksheet’s columns :
The userform that we created to hide the columns in the workbook and unhide the hidden columns contains also a button to minimize userform. With to the drop-down list in the userform can be navigated between worksheets, the selected worksheet from the combobox is active and the column management(hide-unhide) of this worksheet is provided.
Explanations and sample Excel file here

Row selection and copying with a button

I am trying to use a button in Excel to copy a certain range of cells from the active workbook to another workbook. The copying works perfectly when I specify a fixed range for each button in its assigned Macro but I'm stumped as to how to use the same Macro on each button and for the button's row number to indicate the row of data to be copied.
Every row contains 6 or so cells with the 7th containing the button. When the user presses this button the 6 cells on the same row as the row containing the pressed button need to be copied.
I am a complete novice when it comes to VBScript but much googling has got me this far:
Sheets("SurfaceThreats").Range("A4:F4")Copy_
Sheets("ORBAT").Cells(Rows.Count,1).End(x1Up).Offset(1,0)
Surely there is a more elegant solution than assigning a different, fixed range, Macro to every button.
See this screenshot
And this is the code for the Select Row(s) button
Option Explicit
Private Sub CommandButton1_Click()
Dim Ret As Range, rng As Range
Dim lRow As Long
On Error Resume Next
Set Ret = Application.InputBox("Please select the row", Type:=8)
On Error GoTo 0
If Not Ret Is Nothing Then
For Each rng In Ret.Rows
'~~> Get the last row in sheets "ORBAT" where you want to copy
With Sheets("ORBAT")
lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
End With
'~~> Copy the rows
Sheets("SurfaceThreats").Range("A" & rng.Row & ":F" & rng.Row).Copy _
Sheets("ORBAT").Cells(lRow, 1)
Next
End If
End Sub
You can't create a generic button handler, but you can dynamically create the buttons and the macros to handle them. But it's quite a lot of work and you'll have to start creating macros dynamically. (this can cause problems with anti-virus software sometimes i think).
You could use the Worksheet_OnBeforeDoubleClick event to create "fake" buttons
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Target.Worksheet.Columns(1)) Is Nothing Then
MsgBox "You Clicked " & Target.Address
' call your generic handler here passing the Target.Address or Target.Row
Cancel = True
End If
End Sub
Using this code, if you double click any cell in the "A" column you'll get a message box saying what cell you clicked.
Its not the best of ideas, some users might not understand that it is a button.

How to highlight calculated fields in an Excel spreadsheet?

Is there a simple way to do this, via macro or otherwise? By calculated field I mean a field that is computed from other fields, versus raw entered values. By highlight I mean colored differently. I need this to better understand a large spreadsheet from a client.
To do it manually, press the F5 key to bring up the GoTo dialog. Click the Special Cells button. On the next screen, select Formulas (it's an option on the right).
Excel will select all of the cells that match. Now it's just a matter of applying formatting.
I'm going to assume you're only talking about cell formulas rather than VBA calculations here, since you could set the cell colour in your VBA procedure if you're doing it that way.
The way to do this is to check the cell for a formula after you're done with it, and change it's colour at that point. The relevant event here is Change, and the cell's HasFormula property will tell you whether the cell is a literal value, or calculated from a formula:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.HasFormula Then
Target.Interior.Color = vbRed
Else
' remove background colour entirely (i.e. No Fill)
Target.Interior.ColorIndex = xlColorIndexNone
End If
End Sub
TLDR;
Use Conditional Formatting with a Formula to highlight all cells that contain a formula.
Details
In MS Office 365 Version: 5.0.4667.1002, the following works
Select a range of cells.
Case1: Use Ctrl + A to select all cells.
Case2: Select a specific range.
Go to the Home tab, Styles section, and choose Conditional Formatting > New Rule.
The "New Formatting Rule" dialog will open.
Choose "Use a formula to determine which cells to format"
In the textbox, add the following rule: =IsFormula(A1)
Case1: If you selected all cells, use A1 because it is the first cell.
Case2: If you selected a specific range, replace A1 with the first cell in your range.
Click Format...
The "Format Cells" dialog will open.
Choose the format you would like to apply. E.g. a yellow background.
Click OK.
All cells that have formulas will now have, for instance, a yellow background.
Screenshot
Excel has a built in feature of "Trace Dependents" (which shows arrows to show you the calculated cells)
Select the range containing your data.
Excel 2007 -> Formulas -> Trace Dependents
The code below should cycle through each sheet, highlighting every cells that starts with an '=' and colors it the desired color (currently colour 36 which is Light Yellow).
Sub HighLightFormulas()
Dim objSheet As Worksheet
Dim strOriginalSheet As String
Dim intMaxBlankCells As Integer
Dim intBlankColumns As Integer
Dim intBlankRows As Integer
Dim intCurrentColumn As Integer
Dim intCurrentRow As Long
intMaxBlankCells = 40
strOriginalSheet = ActiveSheet.Name
For Each objSheet In Worksheets
intBlankRows = 0
intCurrentRow = 1
intCurrentColumn = 1
Do While intCurrentRow <= 65536 And intBlankRows <= intMaxBlankCells
intBlankColumns = 0
intCurrentColumn = 1
Do While intCurrentColumn <= 256 And intBlankColumns <= intMaxBlankCells
If Left(objSheet.Cells(intCurrentRow, intCurrentColumn).Formula, 1) = '=' Then
objSheet.Cells(intCurrentRow, intCurrentColumn).Interior.ColorIndex = 36
End If
intCurrentColumn = intCurrentColumn + 1
Loop
If intCurrentColumn = intBlankColumns Then
intBlankRows = intBlankRows + 1
Else
intBlankRows = 0
End If
intCurrentRow = intCurrentRow + 1
Loop
Next objSheet
Worksheets(strOriginalSheet).Activate
Call MsgBox("The Highlighting process has completed", vbOKOnly, "Process Complete")
End Sub
It will also stop after 40 consecutive blank cells (to avoid processing all of a mostly blank sheet).
Hope this helps.
Simple solution:
Ctrl - ` (the key just above Tab)
You can use the Interior.ColorIndex property to change the active cell's background color:
ActiveCell.Interior.ColorIndex = 36
You may also apply it to a range:
Range("A1:A5").Interior.Color = RGB(200,160,35)
This applies to Excel 2003, I haven't used the latest version but I doubt this has changed.
You can usually record a macro and then look at the generated code to see how something is done.
I liked Craig's code here, because it keeps the layout of the existing worksheet and yet shows what is calculated and what is not 'at a glance', but I have reworked it a bit so it does a better job of working out the active area of sheets, and I added an 'UnhighlightFormulas' subroutine so one can easily undo the formatting (e.g. before printing). It has been tested in Excel 2007. Note that you will lose any other cell background colouring upon running this.
Option Explicit
Public Sub HighlightFormulas()
ColorFormulas (36) '36 is yellow
End Sub
Public Sub UnhighlightFormulas()
ColorFormulas (-4142) '-4142 is default
End Sub
Private Sub ColorFormulas(intColor As Integer)
Dim wshSheet As Worksheet
Dim rngRange As Range
Dim rngCell As Range
For Each wshSheet In Worksheets
Set rngRange = RangeInUse(wshSheet)
If Not rngRange Is Nothing Then
For Each rngCell In rngRange
If Left(rngCell.Formula, 1) = "=" Then
If rngCell.Interior.ColorIndex <> intColor Then rngCell.Interior.ColorIndex = intColor
Else
If rngCell.Interior.ColorIndex <> -4142 Then rngCell.Interior.ColorIndex = -4142 '-4142 is default
End If
Next
End If
Next
End Sub
Private Function RangeInUse(ws As Worksheet) As Range
Dim LastRow&, LastCol%
' adapted from http://www.beyondtechnology.com/geeks012.shtml
' Error-handling in case there is no data in worksheet
On Error Resume Next
With ws
LastRow& = .Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
LastCol% = .Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
End With
Set RangeInUse = ws.Range("A1", Cells(LastRow&, LastCol%))
End Function

Resources