添加后选择列

时间:2017-04-19 23:08:33

标签: excel vba excel-vba

它从另一个页面的模板中添加一个新列,以便复制公式和格式。它在最后一列之前添加1列。最后一列正在使用锚。我希望它选择并转到myCol & "5",但我无法让它工作。

Function GetColumnLetter(colNum As Long) As String
    Dim vArr
    vArr = Split(Cells(1, colNum).Address(True, False), "$")
    GetColumnLetter = vArr(0)
End Function

Sub NewPlate_F() 'Insert Column Button
    Application.ScreenUpdating = False

    Dim sht8 As Worksheet
    Set sht8 = ThisWorkbook.Worksheets("Add")
    Dim sht2 As Worksheet
    Set sht2 = ThisWorkbook.Worksheets("Foundation Plates")

    Call Unprotect
    sht2.Activate

    Dim lastCol As Long
    Dim myCol As String
    Dim rng As Range
    Dim cell As Range

    With sht2
        Set rng = Cells

    lastCol = sht2.Cells(5, sht2.Columns.Count).End(xlToLeft).Column
    myCol = GetColumnLetter(lastCol)

    Set rng = sht2.Range(myCol & "5")

    'MsgBox rng.Address

        With sht2
        Columns(myCol).EntireColumn.Insert
        Columns(myCol).ColumnWidth = 13
            Application.Wait (Now + 0.000005)
        sht8.Range("H7:H48").Copy Range(myCol & "1")
        Range(myCol & "5").Select
        End With
    End With


    Call Format_Foundation
    Call Unprotect

    With sht2
        Range(myCol & "5").Select
    End With
    sht2.Activate

    Set sht2 = Nothing
    Set sht8 = Nothing
    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:2)

试一试,

With sht2
    .Activate
    .Range(myCol & "5").Select
    '... or,
    .Cells(5, lastCol).Select
End With

请注意我使用带有..Cells(...)的前缀.Range(...)。当你在With ... End With时,前缀句点(例如)将父工作表引用传递给.Range或.Cells属性。

阅读How to avoid using Select in Excel VBA macros是值得的。