在 Excel VBA 中设置多列的列宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44761418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:47:30  来源:igfitidea点击:

Setting a column width on multiple columns in Excel VBA

excel-vbavbaexcel

提问by Maccus

Jeeped and CLR kindly provided the code that added a variable number of columns to a worksheet named sht02AnalysisSummarystarting at Column D whilst copying the borders and formulae of Column C.

Jeeped 和 CLR 好心地提供了将可变列数添加到名为sht02AnalysisSummary的工作表中的代码,该工作表从 D 列开始,同时复制 C 列的边框和公式。

AddCol = txtNrEvaluated

With sht02AnalysisSummary
    Set rangeCopy = .Range(.Cells(3, "C"), .Cells(.Rows.Count, "C").End(xlUp))
    rangeCopy.Copy Destination:=.Cells(3, .Columns.Count).End(xlToLeft).Offset(0, 1).Resize(rangeCopy.Rows.Count, AddCol)
End With

This code, however, does not copy the format of Column C in terms of width and although I have experimented with EntireColumn.ColumnWidth = 15with the With End Withand even its own With End With, I have been unsuccessful.

而下面的代码,不会复制C列的格式在宽度方面,虽然我已经试验过EntireColumn.ColumnWidth = 15With End With,甚至自己的With End With,我一直不成功。

Any assistance would be much appreciated.

任何帮助将不胜感激。

回答by Siddharth Rout

Expanding on my comment below your question.

在您的问题下方扩展我的评论。

Column Widths are only copied across when you are copying across entire columns and nor ranges. Also rng.ColumnWidth = 15should work

仅当您跨整个列和范围复制时,才会跨列宽度复制。也rng.ColumnWidth = 15应该工作

Is this what you are trying?

这是你正在尝试的吗?

Dim rangeCopy As Range, destRng As Range

AddCol = 2

With sht02AnalysisSummary
    Set rangeCopy = .Range(.Cells(3, "C"), .Cells(.Rows.Count, "C").End(xlUp))
    Set destRng = .Cells(3, .Columns.Count).End(xlToLeft).Offset(0, 1).Resize(rangeCopy.Rows.Count, AddCol)
    rangeCopy.Copy destRng
    destRng.ColumnWidth = 15
End With

Screenshot

截屏

enter image description here

enter image description here

回答by CLR

If you want to copy the source tab's column C width across to the new columns, you could use:

如果要将源选项卡的列 C 宽度复制到新列,可以使用:

Dim rangeCopy As Range, rangePaste As Range
Dim Addcol As Integer

Addcol = NrEvaluated

With sht02AnalysisSummary

    Set rangeCopy = .Range(.Cells(3, "C"), .Cells(.Rows.Count, "C").End(xlUp))
    Set rangePaste = .Cells(3, .Columns.Count).End(xlToLeft).Offset(0, 1).Resize(rangeCopy.Rows.Count, Addcol)

    rangeCopy.Copy Destination:=rangePaste
    rangePaste.EntireColumn.ColumnWidth = rangeCopy.EntireColumn.ColumnWidth

End With