Why does the units of Range.ColumnWidth not match either points or Centimeters (default unit used) - excel

I am producing a VBA subroutine in an Access database which generates an Excel File however when I modify the column widths using:
Range("A:A").ColumnWidth = ...
Produces mixed results depending on the unit of measurement. Excel's default measurement set in options is Centimeters. I have tried entering the value in points and in cm but the result is either too wide or too small (see below):
Range("A:A").ColumnWidth = 3.07 'In Centimeters - Too small
Range("A:A").ColumnWidth = 87.02 'In Points - Too big
According to the documentation
Range.ColumnWidth
is set using the measurement in the points unit of measurement (width of 0). Regardless of the value I enter the result isn't the same.

The .ColumnWidth property refers to the number of zeros you can type in a cell in the default font without exceeding the cell's width.
In a new workbook where presumably your default column width is 8.43, type '000000000 in a cell and you'll see that the 9th zero overflows the right cell border by about half a zero.
To set the cell width in points, set .ColumnWidth to points / cell.Width * cell.ColumnWidth. Here's the catch, you have to set it three times to get it close, but it will almost never be exact. So put the .ColumnWidth assignment in a For Next loop and set it three times.
Note that the .Width property is in points and you can't set it. The .ColumnWidth property is in crazy-zero-width-measurement and you can set it. Why it takes three times, I don't know.
See http://dailydoseofexcel.com/archives/2004/06/01/column-widths-in-points/ for some test results on the 'three times' thing.

Related

How to adjust column width in Excel (.Width not .ColumnWidth)

When I use the code
ActiveSheet.Range("b:Az").ColumnWidth = 5
MsgBox ActiveSheet.Range("d1").ColumnWidth
it shows 5, but when using
ActiveSheet.Range("b:Az").ColumnWidth = 5
MsgBox ActiveSheet.Range("d1").Width
it shows 30
I know that the two properties are not the same (for some reason that I can't understand), but I want actually to adjust the property .Width not .ColumnWidth for some calculations in my code, but Excel refuses to adjust .Width property and shows Error '1004' (unable to adjust with property) when I run the following code:
ActiveSheet.Range("b:Az").Width = 5
so, how to adjust .Width property?
width can not be set -see here
[https://learn.microsoft.com/en-us/office/vba/api/excel.range.width][1]
width gives you the width in pixel.
columnWidth can be set, according to ms-page: One unit of column width is equal to the width of one character in the Normal style

Zoom couple of columns to fit page with VBA

I'm having trouble fitting my columns in Excel on a sheet.
I have a sheet with columns from A to CK (can be different per project).
I don't need to print column A, but column B has to be on all pages and next to column B has to be 3 columns. So that will make column "B,C:E" on first page, next page "B,F:H", and so on... Column B is set as title, so it will be printed on every page.
My problem is to set the scale. What I'm doing:
Take pagesize and translate to points, take off margin left and margin right = my printable area
Get the width of range("B:E") = my range to fit the page
Divide my printable area by my range to fit, multiply that with 100%, and extract 1% to make sure it will fit
The outcome in my situation is 83, but is has to be 77 to fit the page. I'll have to find other numbers I think, but I don't know how and which...
My code:
If ActiveSheet.Name = "Meterkastlijst" Then
Dim lngZoom As Long
Dim lngKolB As Long
Dim lngPagB As Long
lngKolB = ActiveSheet.Range("B:E").Width
If ActiveSheet.PageSetup.PaperSize = xlPaperA4 Then
lngPagB = CLng(Application.CentimetersToPoints(21)) - CLng((ActiveSheet.PageSetup.LeftMargin + ActiveSheet.PageSetup.RightMargin))
ElseIf ActiveSheet.PageSetup.PaperSize = xlPaperA3 Then
lngPagB = CLng(Application.CentimetersToPoints(29.7)) - CLng((ActiveSheet.PageSetup.LeftMargin + ActiveSheet.PageSetup.RightMargin))
End If
If lngPagB <> 0 And lngKolB <> 0 Then
lngZoom = ((lngPagB / lngKolB) * 100) - 1
With ActiveSheet.PageSetup
.Zoom = lngZoom
End With
End If
End If
Different widths:
Column B: 45 (319 pixels) -> in Excel, set with VBA
Column C: 15 (109 pixels) -> in Excel, set with VBA
Column D: 30 (214 pixels) -> in Excel, set with VBA
Column E: 20 (144 pixels) -> in Excel, set with VBA
Column B-E: 589 points -> with VBA
Page: 21 centimeters (595 points)
Margins (left & right): 1.8 centimeters (50.4 points)
Print area: 595 - 101 (100.8) = 494 points
With numbers above it calculates 83%, but then it doesn't fit, when I set it manually to 77% it does fit, but how can I get this number with VBA? I don't understand the column widths, what I see in Excel and how I set it in VBA (45+15+30+20) is different from what VBA tells me it should be (589)...
Column Width Units
Column width is measured in Characters, Points, Centimeters / Inches, Pixels, ...
Column width in Characters
If you set a column width by manual value input or by mouse, you see the "amount of standard font number characters". Please refer to Microsoft support for details.
This value can be read and written in VBA: .Range.ColumnWidth = 10.78.
The maximum value is 255.
Column width in Points
This is an internal value not shown in GUI during manual resize of a column.
It corresponds to 72 points per inch.
In VBA it can only be read: .Range.Width
Column width in Pixels
Excel shows the column width in pixels (in parentheses) during manual resize of a column width in normal view. This value can not be read or written directly in VBA.
Column width in Centimeters or Inches
During manual resize within the page layout view Excel shows column width in centimeters (or inches) instead of pixels.
Only this value depends on print zoom level!
The measurement unit itself can be read in VBA:
Application.MeasurementUnit ' 0 = xlInches, 1 = xlCentimeters, 2 = xlMillimeters
Conversion Formulas
By this you may check or verify all values in your environment:
Dim ScreenResolution As Double
Dim ColumnWidthChars As Double
Dim ColumnWidthPoints As Double
Dim ColumnWidthPixels As Double
Dim ColumnWidthInches As Double
Dim ColumnWidthCentimeters As Double
ScreenResolution = 120 ' normal (96 dpi) or large (120 dpi)
ColumnWidthChars = ActiveSheet.Columns(1).ColumnWidth
ColumnWidthPoints = ActiveSheet.Columns(1).Width
ColumnWidthPixels = (ColumnWidthPoints / 72) * ScreenResolution
ColumnWidthInches = ColumnWidthPoints / 72 * ActiveSheet.PageSetup.Zoom / 100
ColumnWidthCentimeters = ColumnWidthInches * 2.54
Debug.Print ColumnWidthChars, ColumnWidthPoints, ColumnWidthInches, _
ColumnWidthCentimeters, ColumnWidthPixels
ScreenResolution may be retrieved with API function GetDeviceCaps(hDC, 88)
Rounding Effects
Excel stores the character-based .Range.ColumnWidth with decimals for each relevant column in the workbook file. If you set it to 100, it is stored as e. g.
<cols><col min="1" max="1" width="100.77734375" customWidth="1"/></cols>
After reopening this file, the reported .ColumnWidth is 100 without decimals.
If you set a large column width and switch between normal view and page layout view, then you may register difference of about 2% between the measures (.Range.Width and pixels suddenly change) - but all values still correspond to each other according to above formulas.
Display Scaling Dependency
All different column width values are independent of Excel's view zoom level and/or Windows 10 display scaling.
Print Zoom Dependency
Only the inch- and centimeter values change, if you change the print zoom level.
But you get more or less columns i. e. amount of points on your paper.
Excel measures .PageSetup.Leftmargin in points (with a scale of 72 points per inch). This corresponds to .Range.Width which is also measured in points.
Example: If I set both paper margins to 5.5 cm, then the resulting A4 paper width of 10 cm holds e. g. two columns with a total .Width of appr. 283 points which corresponds to 72 points/inch.
If I set the print zoom to 83 percent a .Width of appr. 340 points is maximum, and at a print zoom of 30 % it's almost 943 points.
Print Scaling
The calculation of a print zoom factor is
WorkSheet.PageSetup.Zoom = (PageWidthInPoints / AllColumnsWidthInPoints) * 100
Your calculation seems to be correct, but I would subtract at least 2 % (see rounding effects above).

Retrieve top 10 results from a data set by category

The data set I have is for example and the actual data will have upwards of 100 people. I need to retrieve the top 10 scores from each category in the picture below:
I think the answer is really quite simple.
In each of the corresponding cells, use the "large" forumla.
In cell for vertical 1 it would read large(column vertical, 1) - Returning the largest value in the set.
In cell for vertical 2 it would reage large(colum vertical, 2) - Returning the 2nd largest value in the set.

Setting maximum and minimum values for x-axis in Excel

I have a graph that has dates on the x-axis and I'm trying to set maximum and minimum values for this axis using an Excel VBA. I defined MinXAxis and MaxXAxis values in the same sheet and here is my code:
Sub UpdateChartAxes()
With ActiveSheet.ChartObjects("Chart 1").Chart
.Axes(xlCategory).MinimumScaleIsAuto = False
.Axes(xlCategory).MinimumScale = Range("MinXAxis").Value
.Axes(xlCategory).MaximumScaleIsAuto = False
.Axes(xlCategory).MaximumScale = Range("MaxXAxis").Value
End With
End Sub
When I run this code I get error 400 with no explanation about the error.
Any ideas what might be going wrong?
Axis.MinimumScale Property
Returns or sets the minimum value on the value axis. Read/write
Double.
You should be applying these properties to the value axis xlValue, not the Category axis.
Setting this property will also set MinimumScaleIsAuto = False so you won't need those lines.
Added If you use a column, bar, line, etc., graph then these have a Value and a Category axis. You can only set the Minimum or Maximum for the Value axis. Even if you swap them around (x - y) there is still only one Value and one Category axis. Edited An exception to this is if dates are used as the Category axis, in which case Excel enables the Scale settings, as it recognises them as values.
If, instead, you use a Scatter graph, then this has both X-Values and Y-Values, and each of these value axes can be given maxima and minima.
By far the easiest way to prove all this is to double click on an axis and see whether the Axis Options allows you to set a minimum and maximum.
At the beginning of the code, add
On Error GoTo ShowErrDescription.
After End With and before End Sub, add the following code
Exit Sub
ShowErrDescription:
MsgBox Err.Description
This should at least give you a little more information about the error.

How to plot chart values outside axis maximum?

In previous versions of Excel there was a registry entry that you could create to allow Excel to display values/labels that would be positioned outside the axis min/max using QFE_Bonn dword=1. This is what I have used for Excel 2003: Plot lines that contain labels disappear ...)
I have not been able to find a similar patch or native functionality in Excel 2010 (Office Pro Plus). Any ideas how this can be accomplished, or did MS remove this functionality altogether?
Here are screenshots of examples in Excel 2003. I create a series of data which uniformly exceeds the y-axis maximum. This series' color fill has been removed already
To finish the look, remove the series' border so that it appears invisible. Then replace the series' value labels with the relevant data.
There is a workaround using the DataLabels.Left property which positions the DataLabel relative to the ChartArea.
Here is an example VB solution:
sub FakeLabels()
Dim sF As Double
Dim lOff As Double
Dim p As Double
ActiveSheet.ChartObjects(1).Activate
With ActiveChart
For sF = 1 To .SeriesCollection.Count
If .SeriesCollection(sF).Name = "FakeSeries" Then
'Define the lOff variable by adding 100, or some other value
lOff = .SeriesCollection(sF).Points(1).DataLabel.Left + 100
For p = 1 To .SeriesCollection(sF).Points.Count
.SeriesCollection(sF).Points(p).DataLabel.Left = lOff
Next p
End If
Next sF
End With
It yields the same results, the only new requirement is to keep the values for the "dummy" series within the axis min/max values for the chart.
A pleasant surprise is that re-sizing the chart doesn’t appear to affect the relative placement of the labels.
UPDATED 9-25-2013
I have used the "textbox" approach since first asking this question. But it is extremely clunky to manage the interplay between the labels' position and the textbox positions, their relative position of the PlotArea i.e., when to use .InsideWidth vs. .Width or .InsideLeft vs. .Left and whether there needs to be any sort of hedonic "adjustments" to the points values, as always seem to be the case, they are never quite perfectly aligned.
While perusing the PPT object model reference for some other chart-related inquiries, I stumbled upon this property which appears to replicate the functionality of the previous hotfix/registry hack.
.ShowDataLabelsOverMaximum

Resources