B. Clay Shannon B. Clay Shannon - 11 months ago 38
C# Question

Why does attempting to autofit the width of a sheet, or a single column on that sheet, fail?

I have one column whose contents are truncated, and I'd like to avoid having to 2-click the right column gutter to see the data. First I tried autofitting the entire shebang:

private void PopulatePivotTableDataSheet()
if (null == _produceUsagePivotDataList) return;
foreach (ProduceUsagePivotData pupd in _produceUsagePivotDataList)
AddPivotData(pupd.ItemCode, pupd.ItemDescription, pupd.Unit, pupd.MonthYear, pupd.Quantity,
pupd.TotalPrice, pupd.IsContractItem);

...but the last line fails with "AutoFit method of Range class failed"

Then I tried applying it to just the column in question like so:

private void AddPivotData(String ItemCode, String ItemDescription, String Unit, String MonthYear, int Quantity, Decimal TotalPrice, Boolean IsContractItem)
var itemCodeCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 1];
itemCodeCell.Value2 = ItemCode;

var itemDescriptionCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 2];
itemDescriptionCell.Value2 = ItemDescription;
. . .

...and that last line fails with, "'System.__ComObject' does not contain a definition for 'AutoFitWidth'"

What in Sam Hill o' beans is going on here? Autofitting should be easily doable, shouldn't it?

Answer Source

This will apply AutoFit to the columns comprising the range: