Bar Charts
This type creates a stacked bar chart with the first series being the duration from project start to task start. This series’ fill color is set to “No Fill” so it appears that the second series – the actual task – is floating by itself. It is a clever and effective means to small Gantts – about 30 or less tasks. It can leverage XL2007 and later’s improved aesthetics.
Conditional Formatting
This type uses spreadsheet cells and conditional formatting to make colored cells into Gantt Chart bars. This method can accommodate many more tasks but also creates a lot of formulas and calculations.
Introducing BabyGantt.xls
BXL’s Baby Gantt uses shapes and VBA. It has the advantage of Conditional Formatting’s “many tasks” without the formula overhead. It also shares the Bar Chart’s improved graphics capabilities. But best of all, there’s no setup – at least – not for the chart.
All Gantt Charts require tasks and dates. But that’s all Baby Gantt requires us to enter. We don’t need to add and configure charts or enter and autofill formulas across massive ranges. The VBA in Baby Gantt reads our task entries and generates the graphics on the fly. And because it is Excel, we can use formulas to calculate task start and end dates.
DIY
You can build BabyGantt.xls yourself or download it from my DropBox. Here is a link to the instructions:
https://dl.dropboxusercontent.com/u/13737137/Projects/Gantt/BabyGantt.pdf
The instructions include:
Moma Gantt Testers Wanted!
If you would like to be part of the MomaGantt.xls test team please email me at Craig_Hatmaker at Yahoo.com
To read simple Data Areas from SQL we need a little help from IBM’s iSeries. We need a “stored procedure” which we must create, which means we must program on the iSeries. This post assumes you have access to your iSeries via a “green screen”. If you don’t know what I’m talking about, bale now because this won’t make any sense to you.
Procedure:
I’m going to use an example to help explain things. In this example imagine we have a data area containing a numeric ID. The steps to create this stored procedure are:
The first step is to write the CL source. Let’s put it in member GetMyData in QGPL/QCLSRC. Here is the example:
PGM PARM(&ID) DCL VAR(&ID) TYPE(*DEC) LEN(10 0) RTVDTAARA DTAARA(MYDATA) RTNVAR(&ID) ENDPGM
The next step is to create the CL Module. At a command prompt type:
CRTCLMOD MODULE(QGPL/GetMyData) SRCFILE(QGPL/QCLSRC)
After the above executes succesfully, type this command:
CRTSRVPGM SRVPGM(QGPL/GetMyData) MODULE(QGPL/GetMyData) EXPORT(*ALL)
Next we write our SQL Script. Create source member GetMyData in QGPL/QDDSSRC:
Create Function GetMyData() Returns DECIMAL(10, 0) Language CL Specific GetMyData Deterministic No SQL Returns Null on Null Input No External Action Not Fenced External Name 'QGPL/GetMyData(GetMyData)' Parameter Style SQL;
Lastly, we run the SQL script from a command line:
RUNSQLSTM SRCFILE(QGPL/QDDSSRC) SRCMBR(GetMyData)
Now all that is left to do is test it. Using command STRSQL to start an SQL session, run this SQL statement:
Select GetMyData() From SYSIBM/SYSDUMMY1
SYSIBM/SYSDUMMY1 is a special one record file we can use for this sort of thing.
Summary:
As you can see, there’s not a lot of work involved once you know how. And if you look carefully, you can see many possibilities for doing things far beyond reading simple data areas!
References:
Dynamic | Tables grow/shrink as rows/columns are add/deleted. |
Nieghbor Aware | Tables automatically move other tables as they grow (with some restrictions) |
Structured References | In Excel 2007 and higher (XL’07+), tables create special names so we can address a table’s column by its heading. Ex: =Table[Column] |
Stylish | Table Styles (in XL’07+) dramatically improve data formatting. |
Links | They can link to external data. |
Duplicate Removal | XL’07+ includes a menu option to remove duplicate rows. |
Creating tables is easy. If you have a range that contains data, simply select any cell in the range and use the keyboard shortcut: CTRL-L (in XL2007 and later you can also use the more intuitive CTRL-T). Once a table has been created, you can change its name by selecting any cell in the table and using the menu tab Table Tools. The Table Name input box is on the left in the Properties grouping.
Tables have some drawbacks.
Not Supported Prior to XL’03 | So if you’re using old versions of Excel, use the “Mr.Excel” or “Excel is Fun” approach – or upgrade and start using Excel’s Tables. |
External Data Source Restriction | MS Query and Data Validation can’t see tables without a Named Range Wrapper. |
A Named Range Wrapper (NRW) is simply a name assigned to a range. To create an NRW for a table just select the table’s entire range and assign a name by typing it into Excel’s Name Box or using the menu path Formulas > Define Name. If you are working with a .xls, you’re done. But if you’re working with a any of the new formats (.xlsx, .xlsm) you must change the name’s Refers to: reference from a table reference to A1 notation. That’s it. The new range is every bit as dynamic as the best dynamic named range formula – without the formula.
“Can there be Dynamic Ranges for VLOOKUP?”
In XL’07+ VLOOKUP works with tables already. If you have a table called “Products” you can use it in VLOOKUP like this:
=VLOOKUP(“ABC”, Products, 2, 0)
Where “ABC” is the value in the first column of Products you’re searching for. In XL’03 VLOOKUP needs an NRW. Once the NRW is created, we use it as we did above.
“Can there be Dynamic Ranges for Data Validation?”
Data Validation does not recognize tables but we can still use them. We can either apply a “Named Range Wrapper” over the table and use the name in Data Validation or we can exploit a quirk of using tables.
QUIRK! Any reference placed over a table becomes dynamic, even absolute cell addresses.
So if we have a table in cells $A$4:$C$10 and we want our Data Validation rule to use the first column’s values (excluding the header) as a list, we can put =$A$5:$A$10 in Data Validation’s Source: box. Now if we add entries to our table, the Source box’s values will change automagically! How cool is that!
Summary:
Clearly, tables are far simpler than the “Mr.Excel” and “Excel is Fun” approaches (both good approaches, both compatible with older XL, neither requiring VBA). Note that we will never have to worry about other tables on the worksheet like we would with the traditional “COUNT” approaches. We don’t have to worry about the table’s location – ever. We don’t have to worry about blanks, or numeric data, or character data or any combinations thereof that can throw off COUNT methods.
Everyone in our office has a computer. Everyone uses Outlook. All we needed was a quick way to get all user names into Excel to edit, format and print. This is different from the contact list. The contact list may, or may not have all users in it and it definitely has far more names than users.
NOTE! Requires Excel 2003 or later because of ListObject
Sub Network_Users()
‘ Date Ini Modification
‘ 04/10/11 CWH Initial Programming
‘ 04/03/14 CWH Added email addresses
Dim olA As Object ‘Outlook.Application Start Outlook (OL)
Dim olNS As Object ‘Namespace OL identifiers context
Dim olAL As Object ‘AddressList An OL address list
Dim olAE As Object ‘AddressEntry An Address List entry
Dim lo As ListObject ‘An Excel Table
On Err GoTo ErrHandler
‘ Create a ListObject/Table in the spreadsheet
With ActiveSheet
.Cells.ClearContents ‘Clear worksheet completely
.Cells.ClearFormats ‘Clear formats as well
[A4:B4] = Array(“Names”,”Email”) ‘Add a column headings
Set lo = .ListObjects.Add(1, [A4].CurrentRegion, , xlYes)
lo.Name = “Names”
End With
‘ Open Outlook, set context, open “All Users” address list
Set olA = CreateObject(“Outlook.Application”)
Set olNS = olA.GetNamespace(“MAPI”)
Set olAL = olNS.AddressLists(“All Users”)
' Add each address entry name to the Excel Table For Each olAE In olAL.AddressEntries With lo.ListRows.Add .Range(1) = olAE.Name .Range(2) = olAE.GetExchangeUser.PrimarySmtpAddress End With Next
‘ Format Results
lo.HeaderRowRange.Style = ActiveWorkbook.Styles(“Heading 1″)
[A5].Select
ActiveWindow.FreezePanes = True
Cells.EntireColumn.AutoFit
‘ Do this ONLY if you want to close Outlook
’olA.Quit
ErrHandler: If Err.Number <> 0 Then MsgBox _ “Network_Users - Error#" & Err.Number & vbCrLf & _ Err.Description, vbCritical, "Error", Err.HelpFile, Err.HelpContext On Error GoTo 0
End Sub
]]>In 2003, Excel introduced something called a “ListObject” also known as a ”Table”. There are several features packed into Tables, but the main feature of importance in this discussion is their ability to grow or shrink dynamically. Out of the box, a table is a dynamic named range. So why agonize over what formula best creates one?
Creating tables is easy, simply select any cell within the desired range of data and press Ctrl-L (in Excel 2007 or 2010 you can also use Ctrl-T). Excel will probably guess correctly what range you meant but gives you the opportunity to specify exactly what you want. Whenever your selected cell is in a table Excel adds the Table Tools tab to its ribbon. There you can change the table’s name using the convenient “Table Name:” box in the upper left corner.
Unlike formula approaches, tables don’t mind other tables on a worksheet. And Tables come with right click menu functions for adding/inserting/deleting rows/columns. As you add rows or columns, the table automatically encompasses the new data, extends formats and formulas, and when rows are inserted, moves tables below to make room.
Tables are superior to named ranges in every way except one: they can’t be used as datasources. That’s easily overcome. Simply select the range you want to use as a datasource (that can be the entire table, just the data, a column…) and give it a name using the name box in the upper left corner of each worksheet, or using the name manager. The new name is every bit as dynamic as the best dynamic range formula – without the formula.
At the time of this blog post, I still meet Excel fans enthusiastic over dynamic ranges. When asked “why not tables?” I usually get a blank stare. Some point out tables don’t work with all versions of Excel. True enough. But it’s been almost a decade now since XL 2003 came out. I’ve long since upgraded every user in the company I work for to Office 2003 or higher. I’ll bet your company has too. So put your favorite dynamic named range formula in a frame and hang it on the wall with other momentous from your past. It’s time to move ahead with tables.
]]>[kml_flashembed movie="http://www.youtube.com/v/97tZL3TJhWs" width="480" height="292" wmode="transparent" /]
Logos are an easy way to add a sense of professionalism to your work. Splash screens and logos are part of every software product purchased and should be part of every application you provide you customers. Besides, animating logos is fun. It entertains users and sets your work apart from the average Excel programmer. I use them when the workbook first opens. Here’s how it’s done.
Open a blank workbook. Rename the first tab “Data”. This will be the worksheet displayed when our workbook opens. Now get a copy of your company’s logo. Your company’s website probably has one about the right size. Paste it onto the Data worksheet. We need to name it “Logo”. To do that, select it, then use Alt-F11 to get to the Visual Basic Editor. Use Ctrl-G to display the Immediate Window. Type “Selection.Name = “Logo” and hit enter. Now we’re ready to code.
Use Ctrl-R to bring up the Project Explorer. Double click “ThisWorkBook.” That brings up the workbook’s code window. Our first routine must run when the workbook opens so we will code it in the Workbook_Open event. This routine activates the worksheet we renamed “Data”, and passes our “Logo” shape to two routines. The first “Grows” the logo into view. The second spins it once.
Private Sub Workbook_Open() Worksheets("Data").Activate ActiveSheet.Shapes("Logo").LockAspectRatio = False GrowShape ActiveSheet.Shapes("Logo"), 10 SpinShape ActiveSheet.Shapes("Logo"), 10 End Sub
The “Grow” routine expands any shape into view. It first turns off screen updating. This allows us to make changes behind the scenes and display the results when we’re ready. Next, the routine remembers the shape’s dimensions. Then the routine changes the shape’s size, displays it, freezes the screen, and loops back until finished. Before returning, the Grow routine makes sure the shape is exactly as we found it.
The Spin routine is nearly identical. It freezes the screen, remembers the shape’s original dimensions, then alters the shapes size in a loop that simulates the shape spinning around its Y axis. When finished, the routine restores the shape to its original size.
That’s all there is to animating a logo.
Function GrowShape(ByRef Shape As Shape, Step As Integer) As Boolean
' Description:Expands a shape into view
' Parameters: Shape The shape to animate
' Step Larger #s animate faster
' Example: GrowShape ActiveSheet.Shapes("Logo"), 10
' Note: For best results, shape should be hidden before calling
' this routine
' Date Init Modification
' 01/10/11 CWH Initial Programming
Dim lCenterX As Long 'Shape's center X coordinate Dim lCenterY As Long 'Shape's center Y coordiante Dim lWidth As Long 'Shape's width Dim lHeight As Long 'Shape's height Dim l As Long 'Generic Counter for the loop Application.ScreenUpdating = False With Shape 'Remember shape's original dimensions lCenterX = .Width / 2 + .Left lCenterY = .Height / 2 + .Top lWidth = .Width lHeight = .Height 'Animation Loop For l = 0 To lWidth Step Step .Width = l .Height = l * lHeight / lWidth .Left = lCenterX - .Width / 2 .Top = lCenterY - .Height / 2 Shape.Visible = True Application.ScreenUpdating = True Application.ScreenUpdating = False Next l 'Restore shape's original dimensions .Width = lWidth .Height = lHeight .Left = lCenterX - .Width / 2 .Top = lCenterY - .Height / 2 End With Application.ScreenUpdating = True
End Function
Function SpinShape(ByRef Shape As Shape, Step As Integer) As Boolean
' Description:Expands a shape into view
' Parameters: Shape The shape to animate
' Step Larger #s animate faster
' Steps should divide 90 evenly
' Example: SpinShape ActiveSheet.Shapes("Logo"), 10
' Date Init Modification ' 01/10/11 CWH Initial Programming Const Pi = 3.14159265358979 Dim sng01 As Single '1 Degree in Radians sng01 = Pi / 180 Dim lCenterX As Long 'Shape's center X coordinate Dim lCenterY As Long 'Shape's center Y coordiante Dim lWidth As Long 'Shape's width Dim lHeight As Long 'Shape's height Dim l As Long 'Generic Counter for the loop Application.ScreenUpdating = False With Shape .LockAspectRatio = False 'Remember shape's original dimensions lCenterX = .Width / 2 + .Left lCenterY = .Height / 2 + .Top lWidth = .Width lHeight = .Height 'Animation Loop For l = 0 To 360 Step Step .Width = lWidth * Abs(Cos(l * sng01)) .Left = lCenterX - .Width / 2 If l = 90 Or l = 270 Then .Flip msoFlipHorizontal Shape.Visible = True Application.ScreenUpdating = True Application.ScreenUpdating = False Next l 'Restore shape's original dimensions .Width = lWidth .Height = lHeight .Left = lCenterX - .Width / 2 .Top = lCenterY - .Height / 2 End With Application.ScreenUpdating = True
End Function
]]>Many times when a workbook is crammed full of numbers, your data can be difficult to read. This is bad enough when you are sure the data is correct, but If you are supplied a spreadsheet that contains potential errors you really want to be able to detect them so they can be fixed.
A common error in inputting is where your work contains duplicate records. There are a couple of ways we can delete duplicates, but what if you only want to see them rather than delete them? Here is when conditional formatting can help. With this little technique you can make the duplicates jump out at you!
Check out this screen grab below.
See how the duplicate rows are highlighted? In this sheet, the highlighting helps us indentify duplicate invoices.
First you need to go to the conditional formatting dialog as you normally would.
Then in the “Edit the Rule Description” box:
Enter this formula:
=SUMPRODUCT(($B2=$B$2:$B$16)*($A2=$A$2:$A$16)*($C2=$C$2:$C$16))>1
The formula might look complicated, and it kind of is. It relies on a function you might not have seen much called SUMPRODUCT. If you are curious about the function, this article is a great introduction to the topic.
In this formula, SUMPRODUCT will return the sum of rows from rows 2 through 16 where columns A,B and C are equal to the current row. If the result is greater than 1 then the format is implemented on that row.
As you can see, when you are given a spreadsheet containing problems, you don’t always want to nuke error rows, some times you need to know about them so you can deal with the issues at source. Conditional formatting can raise your awareness without changing the content of your spreadsheet. Give it a try!
Yoav Ezer co-authors the technology and productivity blog Codswallop. He is also the CEO of a company that produces PDF to Excel conversion software.
For more Excel tips from Yoav, join him on Facebook or Twitter
]]>Here is a typical formula that could be added in Name Manger for a named range that starts in cell $A$1, has two columns, and can grow to as many rows as entries:
=OFFSET($A$1,0,0,COUNTA($A:$A),2)
Translating this formula for us humans, it says:
I ”Googled” the subject and found many articles on Dynamic Named Ranges. Obviously there is a lot of interest and many examples of their use; however, in every article I read, including those in Microsoft’s MSDN, I kept coming across the same shortcomings:
Most of these limitations are because almost everyone seems to want to use COUNT or COUNTA to determine how many rows should be contained in the range. I found one blogger who used MATCH instead of COUNT. This had the advantage of skipping over empty cells, but still worked only for numbers, or for characters, but not for both (unless you double the formula and the MAX function).
=OFFSET($A$1,0,0,MATCH("",$A:$A,-1),2) 'Finds last character cell
=OFFSET($A$1,0,0,MATCH(1E+306,$A:$A,1),2) 'Finds last numeric cell
The above approaches all work. But no one of them works for all circumstances by itself. And none of the approaches dealt with the stray space after the table’s last row. That’s not good enough. I want one compact formula that requires as little thought as possble that works for as many situations as possible. In researching and experimenting, I accidently stumbled on a quirk regarding formulas stored in names that makes overcoming these problems much simpler. Chip explains this quirk very well.
Defined Name Formulas And Array Formulas by Charles H. Pearson
If you use a formula in a Defined Name, that formula is evaluated as if it were an array formula. There is no way to force a formula in a Defined Name to be evaluated as a non-array formula.
Brilliant! With this bit of knowledge, we can use logical functions that are insensitive to the type of data used (Numbers vs Characters). Here is an array formula that finds the last row in column A containing anything at all (NOTE! The curly brackets are the result of Shift-Ctrl-Enter. For more information on how to enter array formulas see Array Formulas by Charles H. Pearson).
{=MAX(IF($A:$A<>"", ROW($A:$A),0))}
Building on this, we can find the last row within the first four columns that contains anything at all, regardless of which column is longest.
{=MAX(IF($A:$D<>"", ROW($A:$A),0))}
Because logical operators in Excel return 0 for FALSE and 1 for TRUE, we can shorten the formula up a bit, if that’s your preference.
{=MAX(($A:$D<>"")*ROW($A:$A))}
But one problem remains. In my opinion, entries containing only spaces are the same as totally empty cells and as I said before, the above formula finds cells that contain anything at all, including those with just spaces. No worries, this is simple enough to overcome by trimming cells.
{=MAX((TRIM($A:$D)<>"")*ROW($A:$A))}
This formula finds the last cell that contains anything other than just spaces. It doesn’t matter if any of the cells in between are empty. It doesn’t matter if any of the cells are numbers or characters. It doesn’t matter which column is longest. To put it all together, you need to adjust for one more thing, the starting row. I often want my ranges to start in row 4 with totals in row 2. So if you want your range to start somewhere other than row 1, you need to subtract the starting row number and add 1 back for good measure. Here is the final formula that you would enter into Name Manager for a range that starts in $A:$4 and has 5 columns (NOTE! Name Manager does not need the curly brackets since it treats ALL formulas as array formulas no matter what).
=OFFSET($A$4,0,0,MAX((TRIM($A:$E)<>"")*(ROW($A:$A)))-3, 5)
This works. It’s also slow. It’s cumbersome.
Formula approaches just don’t work well. There are just too many ways they can fail and too many limitations. So I looked to VBA. VBA has always had a very simple and elegant way of dealing with dynamic ranges:
Set DynamicRange = Range("A4").CurrentRegion
CurrentRegion finds all adjacent non-empty cells. So if “A4″ is anywhere inside a table, CurrentRegion will identify the entire table. One minor problem is it will also pick up any adjacent cells with stray spaces. But a bigger problem is that when used in a UDF (User Defined Function intended to be used within an Excel formula), CurrentRegion returns only one cell.
A different approach (copied from Andy Pope) can be encapsulated into a VBA routine and used in a UDF context:
Set DynamicRange = Range("A4").Resize(Range("A4").End(xlDown).Row - 1, _ Range("A4").End(xlToRight).column - 1)
End() works as long as there is more than one row and column in the range. If, for example, only one row is in the table, the End() method will find the last cell in the worksheet or the next list.
Going through this exercise was interesting, but utlimately, neither VBA, nor complex formulas are required to create dynamic ranges without ANY of the shortcommings of either. We’ll discuss that after another great Excel tip from Yoav Ezer.
]]>[kml_flashembed movie="http://www.youtube.com/v/-Uu2WqDxLdk" width="480" height="292" wmode="transparent" /]
For beginners: What is ”Drilldown?”
Drilldown is displaying underlying details for a total. This is important because we hope charts and summaries show something we didn’t know and/or expect. When that happens, we want to know why. Displaying what makes up a total helps answer that question.
Doesn’t Excel Support Drilldown Automatically?
In PivotTables and Outline Reports – yes. You can double click any calculated number in these Excel objects and Excel displays the associated rows from their source data range. But if you double click on a Chart/Graph element, the “Format Data Point” dialog box appears. That’s not what my users want. The good news, though, is the very same mechanism that reveals detail beneath PivotTables makes coding drilldown for PivotCharts a snap.
What are PivotCharts?
A PivotChart is a chart over a PivotTable. In the templates provided in this blog, we use PivotTables to summarize data in our extracted rows. PivotTables are extremely flexible and allow the user to slice and dice data in many, many useful ways. The only draw back to PivotTables is they show numbers, not graphs. This is easily overcome by simply creating a chart over the PivotTable. Charts made from PivotTable data, as opposed to simple rows of data, also allow users to slice and dice the underlying data just like the user can with a PivotTable. The only drawback to the PivotChart is that it lacks Drill Down.
Adding Drilldown to PivotTable Charts
This “trick” only works with PivotCharts because it relies on the PivotTable’s ShowDetail property. As mentioned before, you can double click on any calculated result in a PivotTable and it will automatically show the associated detail rows. If you start the Macro Recorder, double click on a PivotTable cell, stop the recorder, and then view the recorded code, you’ll see something like this:
Range("B9").Select
Selection.ShowDetail = True
…where “B9″ is the cell you double clicked. The Selection.ShowDetail = True is what causes the detail to display. Now when you create a PivotChart from a PivotTable, each PivotTable cell becomes a chart element. So what we have to do is figure out which chart element the user double clicked and which PivotTable cell that represents. Then all that’s left to do is use that cell’s ShowDetail property to display the data. As it turns out, this is almost easier done than said.
Determining Which Chart Element was Clicked
Excel provides a simple routine that makes this easy - ActiveChart.GetChartElement. ActiveChart.GetChartElement is a method attached to every chart in Excel. You pass to it the mouse pointer’s X and Y coordinates and it returns the Chart Element Type and two of that Chart Element Type’s properties. Chart Element Types can be the chart’s Title, Legend, Axis, … or a Graph Element. We are only interested in Graph Elements such as a slice in a Pie Chart, a line in a Line Chart, a bar in a Bar Chart, etc. So if ActiveChart.GetChartElement returns anything other than a Chart Element Type of 3 (Graph Element), we know to ignore things and move on. On the other hand, if the user clicked a Graph Element, we want to show the detail. When Chart Element Type is 3, Arg1 is the associated PivotTable row and Arg2 is the column. So to show the detail beneath we use:
ActiveChart.PivotLayout.PivotTable.DataBodyRange. _
Cells(Arg2, Arg1).ShowDetail = True
Capturing Chart Double Click and Mouse Pointer’s X and Y
Every Chart also has a Chart_MouseUp event. Chart_MouseUp fires whenever the user clicks (and releases) the mouse on a chart. Excel also passes a few properties to this event. Two are important to us: X and Y.
We now have all of the pieces to the puzzle. All that’s left to do is put it together. Place this code in the Chart Sheet object:
Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _ ByVal x As Long, ByVal y As Long)
' Description:Drill Down into Pivot Chart's data
' Parameters: Button Mouse botton that was released
' Shift State of SHIFT, CTRL, and ALT keys
' x Mouse pointer X coordinate within Chart
' y Mouse pointer Y coordinate within Chart
' Example: *none - This is an event handler
' Date Init Modification
' 10/04/10 CWH Initial Programming
On Error GoTo ErrHandler Dim ElementID As Long Dim Arg1 As Long Dim Arg2 As Long ' Pass: x, y. Receive: ElementID, Arg1, Arg2 ActiveChart.GetChartElement x, y, ElementID, Arg1, Arg2 ' If data element clicked, show detail If ElementID = 3 Then ActiveChart.PivotLayout.PivotTable.DataBodyRange. _ Cells(Arg2, Arg1).ShowDetail = True ActiveSheet.Cells(2, 2).Select ActiveWindow.FreezePanes = True End If
ErrHandler: If Err.Number <> 0 Then MsgBox _ "Chart_MouseUp - Error#" & Err.Number & vbCrLf & _ Err.Description, vbCritical, "Error", Err.HelpFile, Err.HelpContext On Error Resume Next On Error GoTo 0 End Sub]]>
v = Intersect(ActiveWindow.VisibleRange, Selection)
If you look closely at this routine, the variable “v” is never used. So why is it there? Answer: To cause an error. Purposefully causing an error may sound crazy. Well, there may be a better way, but it’s not crazy. If the newly selected cell happens to be outside the visible window, attempting to intersect the selection with the visible window will fail causing error #91. If that happens, we want to shift the window to display the selection with a call to Position_Window_to_Cursor.
Here is the code.
Function Find_UnLocked_Cell(lRowFrom As Long, lRowTo As Long, _ lColFrom As Long, lColTo As Long, _ lStep As Long) As Boolean
' Description:Find the next unlocked cell
' Parameters: lRowFrom Starting Row
' lRowTo Ending Row
' lColFrom Starting Column
' lColTo Ending Column
' lStep Direction (-1=backward)
' Example: bFound = Find_UnLocked_Cell(Selection.Row, Selection.Row, _
' Selection.Column + 1, _
Range("Data").Columns.Count, 1)
' Date Init Modification
' 01/12/06 CWH Initial Programming
On Error GoTo ErrHandler ' Find_UnLocked_Cell = False 'Assume the Worst Dim lRow As Long Dim lCol As Long Dim v As Variant For lRow = lRowFrom To lRowTo Step lStep For lCol = lColFrom To lColTo Step lStep If Cells(lRow, lCol).Interior.Color <> CellLocked Then Cells(lRow, lCol).Select Find_UnLocked_Cell = True v = Intersect(ActiveWindow.VisibleRange, Selection) Exit Function End If Next lCol Next lRow
ErrHandler: If Err.Number = 91 Then Position_Window_to_Cursor Selection ElseIf Err.Number <> 0 Then _ MsgBox _ "Find_UnLocked_Cell - Error#" & Err.Number & vbCrLf & Err.Description, _ vbCritical, "Error", Err.HelpFile, Err.HelpContext End If On Error GoTo 0
End Function
Function Position_Window_to_Cursor(rngCursor As Range) As Boolean
' Description:Positions the window/pane so the cursor is visible
' Parameters: rngCursor The cursor's cell/range
' Example: bResult = Position_Window_to_Cursor(Selection)
' Date Init Modification
' 12/14/09 CWH Initial Programming
On Error GoTo ErrHandler Position_Window_to_Cursor = Failure 'Assume the Worst Dim iPaneRow As Integer Dim iPaneCol As Integer Dim lRow As Long Dim lCol As Long lRow = rngCursor.Row lCol = rngCursor.Column With ActiveWindow If lRow > .SplitRow + 1 Then iPaneRow = .Panes.Count Else iPaneRow = 1 End If If lCol > .SplitColumn + 1 Then iPaneCol = .Panes.Count Else iPaneCol = 1 End If lRow = rngCursor.Row - _ .Panes(iPaneRow).VisibleRange.Rows.Count + 2 If lRow <= .SplitRow Then lRow = .SplitRow + 1 .Panes(iPaneRow).ScrollRow = lRow lCol = rngCursor.Column - _ .Panes(iPaneCol).VisibleRange.Columns.Count + 2 If lCol <= .SplitColumn Then _ lCol = .SplitColumn + 1 .Panes(iPaneCol).ScrollColumn = lCol End With Position_Window_to_Cursor = Success
ErrHandler: If Err.Number <> 0 Then MsgBox _ "Position_Window_to_Cursor - Error#" & Err.Number & vbCrLf & _ Err.Description, vbCritical, "Error", Err.HelpFile, Err.HelpContext On Error GoTo 0
End Function
]]>