vba VBA复制列的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45814565/
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 13:08:34  来源:igfitidea点击:

VBA to copy width of the columns

excelvba

提问by thankseveryone

The VBA code below copies the data from a source data sheet and pastes it onto a specific sheet. However, I need it to also paste the width of the columns on the source data sheet. Would that be possible? thanks for any help.

下面的 VBA 代码从源数据表复制数据并将其粘贴到特定表上。但是,我还需要它来粘贴源数据表上的列宽。那可能吗?谢谢你的帮助。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim tableName As String
Dim tableRange As Range
Dim TypeOfCosts As String
Application.EnableEvents = False

If Range("X1").Text = "aaaa" Then
    TypeOfCosts = "_bbbb"
ElseIf Range("L3") = "cccc" Then
    TypeOfCosts = "_dddd"
Else
    TypeOfCosts = ""
End If

tableName = Range("Y1").Text & TypeOfCosts & "_Costs"

On Error Resume Next
Set tableRange = Application.Range(tableName)
Debug.Print ThisWorkbook.Names.Count
    If Not (tableRange Is Nothing) And Err = 0 Then
    Range("K9").Resize(10000, 10000).ClearContents
    Range("K9").Resize(10000, 10000).ClearFormats
    tableRange.Copy Destination:=Range("M8")
Else
    Err.Clear
End If
On Error GoTo 0
Application.EnableEvents = True
End Sub

回答by Mrig

If your code is executing as desired then instead of

如果您的代码按需要执行,则代替

tableRange.Copy Destination:=Range("M8")

you may write

你可以写

tableRange.Copy    
With Range("M8")
    .PasteSpecial xlPasteColumnWidths
    .PasteSpecial xlPasteValues, , False, False
    .PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
End With