Automatically set optimal height of visible columns in Excel - excel

I have a fairly large Excel sheet, but I'm only interested in a certain amount of columns at a time. Now some columns contain quite a long text requiring a large cell height. After hiding these columns I wanted to set the cell heights of the visible rows rescaled to the optimum height for better browsing my sheet.
How can these be achieved in Excel either out-of-the-box or with a special rescale VBA Macro?
I'm not an Excel specialist, so any help is welcome her.

You probably have set the cells having long text to "Wrap Text". If you reset this, text is shown in one row now matter how long the content is.
If you do this for all columns that are hidden, Excel is able to calculate the needed height properly:
Sub setheight()
Dim col As Range
For Each col In ActiveSheet.UsedRange.Columns
' Set WrapText to false if column is hidden
col.WrapText = Not col.Hidden
Next
ActiveSheet.UsedRange.EntireRow.AutoFit
End Sub
Unfortunately there is no easy way to trigger this automatically as there is no event that is fired when a column is shown/hidden (yes, there is one, but this is related to the ribbon. If you want to have a look, see Trigger Event in Excel VBA when Row or Column is hidden)
There are numerous ways to trigger the sub, you could for example create a keyboard shortcut to the macro. An alternative that I use sometimes is to create a trigger on DoubleClick on a specific cell or range. I would suggest to run the code when the top row is Double-Clicked. Put the following code into the Worksheet-module
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Row > 1 Then Exit Sub
setheight
Cancel = True
End Sub

Related

How to display SUM of visible cells in a userform label?

I would like to display the SUM of visible cells from column D in a Userform Label, and have it update automatically as the spreadsheet gets filtered.
I have this code
Private Sub SUM_click()
Me.SUM.caption = range ("AA2")
End Sub
This is problematic.
I use a SUM formula in cell AA2.
I’d like to avoid using formulas in any cells, if possible.
The return value isn’t excluding rows which are hidden.
It displays the value after I click on the label.
I want it to display automatically.
Automate display of SubTotals in UserForm
This reveals being not as trivial as it may seem.
Of course you might profit from a sheet's Worksheet_Calculate event
to get subtotals (of visible cells) by means of VBA whenever the (enabled) calculation processes a new result.
This is effective when filtering and/or when changing values, whereas the Worksheet_Change event wouldn't cover filtering.
Private Sub Worksheet_Calculate()
Dim subtotal As Double
subtotal = Sheet1.Evaluate("=Subtotal(109,D:D)") ' argument 109 sums up only visible cells!
Debug.Print "Subtotal: " & Format(subtotal, "0.00") ' display in VB Editor's immediate window
End Sub
... but there's no synchronized event to refresh a label in the Userform's code.
So I suggest the following tricky workaround profiting from the ListBox property RowSource:
add the subtotal formula =SUBTOTAL(109,D:D) to cell AA2
instead of a label ... let a listbox do the display binding it to a .RowSource; whenever a subtotal gets changed this will be reflected in the only list value of the bound listbox.
Defining the appearance via .SpecialEffect = fmSpecialEffectFlat makes the Listbox appear nearly like a label. Small beauty mistake: the background color can't be modified
UserForm code example
Private Sub UserForm_Initialize()
With Me.ListBox1 ' << rename control to any other name
.ColumnCount = 1 ' define columncount
.ColumnWidths = .Width - 8 ' play around with small sizes to avoid scroll bars
.Height = 12
.RowSource = "Sheet1!AA2" ' reference to cell containing subtotal formula
.SpecialEffect = fmSpecialEffectFlat
.ListIndex = 0 ' activate first (and only) record
End With
Tip
To enable concurrent actions like editing or filtering in the table, you need to show the UserForm modeless, e.g. via
With New UserForm1
.Show vbModeless
End With
Alternative suggested in comment
Thx to #norie's hint, it would also be possible to profit from a textbox'es .ControlSource property (having more ressemblance to a label) without the need of further cosmetics. Nevertheless this promising approach needs further (or even more complicated?) steps: a textbox allows inputs which would overwrite the initial formula in the referred cell which isn't wanted.
Possible ways out I won't develop here: prevent key-event entries (have a look into other SO posts) or use the TextBox1_Change event to rewrite the formula each time the textbox got changed (doubtful), place a blocking control over the textbox etc.

How to highlight active row in excel and then return to base background color in VBA

How do you highlight an active row in excel in VBA. and then when another row is selected, return that row to base background color, and highlight the new row.
Also how to clear all rows highlighted, using a clear button on the user form.
so there are tow question here, one to high light and unhighlight active rows, and the other to just clear all high lights by pressing a clear button on the form.
I know I can highlight a row using Ret.EntireRow.Interior.ColorIndex = 6 but i cant find code to unhighlight.
Thanks for your help.
You can use your 'clear all' functionality before changing the color of the row of the cell that you navigated to.
Open the VB Editor and right click --> view code on the worksheet that you want the row highlighting to take place.
Paste in this code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Me.Range("A1:XFD1048576").Interior.ColorIndex = 0
Target.EntireRow.Interior.ColorIndex = 6
End Sub
This code operates as follows: whenever a user changes his or her selected cell(s) on the sheet, the code will first clear the existing highlighting away in the entire sheet and then will apply new highlighting to the row of the target cell the user has moved to.
This line of code:
Worksheets("YourSheetName").Range("A1:XFD1048576").Interior.ColorIndex = 0
Will clear the colors from all cells in the worksheet.
You may want to limit the Range("A1:XFD1048576") to the usable range on your workbook as this will increase performance. On my machine I see a very subtle, but still noticeable, delay in the colors when I move the cells (because I am clearing all cells in the sheet instead of just the ones I want). If you do this, you probably wouldn't want to use the .EntireRow attribute, instead you would have to enumerate how far along the workbook you want the row to be highlighted.
Update
Try this code below, which eliminates the need to clear the entire worksheet. I used .ColorIndex=xlNone instead of setting it to 0 which should preserve your table formatting. I tested in Excel 2010 and I formatted some data as a table, it highlights the correct row and unhighlights the other row as well as leaving the table formatting in tact.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static rr
If rr <> "" Then
With Rows(rr).Interior
.ColorIndex = xlNone
End With
End If
r = Selection.Row
rr = r
With Rows(r).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
The trick is using Static. This allows the variable to continue to exist after termination of the procedure, so it remembers the last row it highlighted and then performs the un-highlight action accordingly.
The procedure first checks to see that rr is set, if it is not then it moves on, if it is then rr represents the row that was previously highlighted.
This can be done without changing the base background color,
In 2 steps,
Set up a conditional formatting rule that highlights an entire row if a certain formula is true.
In the formula field, enter this formula:
=OR(CELL("row")=CELL("row",A1))
Write a macro that recalculates the selected cell(s) when a new selection is made.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Calculate
End Sub
Hit Alt + F11 to get back to Excel and you'll have the active cell's row highlighted with the format you chose, without changing the base colors of the cells.
For detailed explanation visit,
highlighted the entire row of the active cell.

Highlight active row/column in Excel without using VBA?

What I want to achieve is to highlight active row or column. I used VBA solutions but everytime Selection_change event is used I am loosing chance to undo any changes in my worksheet.
Is there a way to somehow highlight active row / column without using VBA?
The best you can get is using conditional Formatting.
Create two formula based rules:
=ROW()=CELL("row")
=COLUMN()=CELL("col")
As shown in:
The only drawback is that every time you select a cell you need to recalculate your sheet. (You can press "F9")
You can temporarily highlight the current row (without changing the selection) by pressing Shift+Space. Current column with Ctrl+Space.
Seems to work in Excel, Google Sheets, OpenOffice Calc, and Gnumeric (all the programs I tried it in).
(Thanks to https://productforums.google.com/forum/#!topic/docs/gJh1rLU9IRA for pointing this out)
Unfortunately, not as nice as the formula and macro-based solutions (which worked for me BTW), because the highlighting goes away upon moving the cursor, but it also doesn't require the hassle of setting it up each time, or making a template with it (which I couldn't get to work).
Also, I found you could simplify the conditional formatting formula (for Excel) from the other solutions into a single formula for a single rule as:
=OR(CELL("col")=COLUMN(),CELL("row")=ROW())
Trade off being that, if you did it this way, the highlighted column and row would have to use the same formatting, but that's probably more than adequate for most cases, and is less work.
(thanks to https://trumpexcel.com/highlight-active-row-column-excel/ for abbreviated formula)
I don't think it can be done without using VBA, but it can be done without losing your undo history:
In VBA, add the following to your worksheet object:
Public SelectedRow as Integer
Public SelectedCol as Integer
Private Sub Worksheet_SelectionChange(ByVal Target as Range)
SelectedRow = Target.Row
SelectedCol = Target.Column
Application.CalculateFull ''// this forces all formulas to update
End Sub
Create a new VBA module and add the following:
Public function HighlightSelection(ByVal Target as Range) as Boolean
HighlightSelection = (Target.Row = Sheet1.SelectedRow) Or _
(Target.Column = Sheet1.SelectedCol)
End Function
Finally, use conditional formatting to highlight cells based on the 'HighlightSelection' formula:
First of all Thanks! I had just created a solution with highlighting cells, using the Selection_Change and changing a cells content. I did not know it would disable Undo.
I found a way to do it by using combining conditional formatting, Cell() and the Selection_Change event. This is how I did it.
In Cell A1 I put the formula =Cell("row")
Row 2 is completely empty
Row 3 contains the headers
Row 4 and down is the data
To make the formula in A1 to be updated, the sheet need to recalculate. I can do that with F9, but I created the Selection_Change event with the only code to be executed is Range("A1").Calculate. This way it is done every time the user moves around, and as the Selection_Change is NOT changing any values/formats etc in the sheet, Undo is not disabled.
Now just enter the conditional formatting to highlight the cells that have the same row as cell A1.
Select the whole column B
Conditional Formatting, Manage Rules, New Rule, Use a Formula to determine which cells to format
Enter this formula: =Row(B1)=$A$1
Click Format and select how you want it to be highlighted
Ready. Press OK in the popups.
This works for me.
An alternative to Range.Calculate is using ActiveWindow.SmallScroll
The only downside is that the screen flickers for a split second after making a new selection.
While scrolling manually, you need to make sure the new selection moves out of the screen (window) completely, for it to work. Which is why, in below code, we need to scroll enough to get all visible rows out of the screen view and then scroll back to same position -to force screen refresh for conditional formatting.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ScreenUpdating = False
ActiveWindow.SmallScroll Down:=150 'change these values to total rows displayed on screen
ActiveWindow.SmallScroll Down:=-150 'change these values to total rows displayed on screen
'DoEvents 'unable to use this to remove the screen flicker
ScreenUpdating = True
End Sub
Credits:
Rory Archibald
https://www.experts-exchange.com/questions/28275889/When-is-excel-conditional-formatting-refreshed.html
Using conditional formatting, instead of highlighting the entire row and column, it is possible to highlight the row to the left of the cell and the column above the cell with the code below:
=OR(AND(CELL("col")=COLUMN();(CELL("row")-1)>=ROW());AND(CELL("col")>=COLUMN();(CELL("row")-1)=ROW()))
On the sheets Selection_change event call the following:
Function highlight_Row(rngTarget As Range)
Dim strRangeRow As String
strRangeRow = rngTarget.Row
strRangeRow = strRangeRow & ":" & strRangeRow
Rows(strRangeRow).Select
rngTarget.Activate
End Function
This is long format for clarity!
also add this code in vba to refresh sheet (instead of F9)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Application.CutCopyMode = False Then
Application.Calculate
End If
End Sub
to highlight the active column and row, up to the cell being clicked, without colouring the cell being clicked, and without colouring the entire column and row, this formula in Conditional Formatting works in Excel:
=OR(AND(CELL("col")=COLUMN(),(CELL("row")-1)>=ROW()),AND(CELL("row")=ROW(),(CELL("col")-1)>=COLUMN()))
Divide the number (to be formatted) by subtotal of itself in another column, which will cause error for hidden items and runtime conditional formatting with Graded Color Scale can be achieved.

Excel filter from other list

I have 2 lists in excel. First one is for searching (i want to have dropboxes), and second list is for data.
In second list I have filtered data. But what I want to do now is filter from parameters given in first list.
How can I transfer filter headers on first page?
I want to select brand on 'Search' list and results will be filtered on 'Rows' list.
I can't think of a way to do this exact thing without VBA. Certainly would love to know if there is a way, so maybe someone else can chime in.
That said, here is a small VBA procedure that will get what you want. It works based off a change in the drop down box for Brand in your Search sheet. Follow steps below to implement:
once in Excel hit Ctrl + F11 on your keyboard. This opens up the VBE
In the Project - VBAProject window in the upper left click the Object referring to the Search sheet
Paste the below code into the big window on the right referring to that sheet.
Make sure to save the file as an .xlsm file (Excel-Macro Enabled File) if using XL2007 or greater.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wksFilter As Worksheet, wks As Worksheet
Dim rngFilter As Range
'replace "A6" with the cell where the Brand dropdown is
If Target.Address = "$A$6" Then
Set wks = Sheets(Target.Parent.Name)
Set wksFilter = Sheets("Rows")
'may need to adjust the number 1 to match the exact location of your Search Column in the rows sheet
wksFilter.UsedRange.AutoFilter 1, wks.Range(Target.Address)
End If
End Sub

Using VB to alter row colour in Excel if checkbox on same row is ticked

I have an Excel spreadsheet listing various courses. I have checkboxes in column F for each course (not for every row - there are some gaps). When a checkbox is ticked I want to alter the color of cells B to E on the same row.
Would there be a way of doing this in one method rather than copying the code for each checkbox?
Any help appreciated as always - thanks!
The checkbox idea will be hard to implement. But if you want to have a clickable way to set the background of the cells in that row you can insert a hyperlink on your course title. Have the hyperlink point to the adjacent cells in that row. So if the title is on B3, have the hyperlink point to C3:E3, for example.
Implement the Worksheet_FollowHyperlink event on your sheet's code-behind. Here is a sample sub to get you started:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim myRange As Range
Set myRange = Range(Application.Selection.Address)
myRange.Interior.Color = RGB(127, 256, 256)
End Sub
This works on Excel 2007. Untested on other versions.
Assign the same macro to all the checkboxes. The issue you may have is trying to figure out what row the checkbox sits on. The controls don't actually sit in the grid. They sit on top of the worksheet and have no reference to the rows.

Resources