2017-04-19 66 views
1

它从另一页的模板添加新列,以便复制公式和格式。它在最后一列之前添加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 

回答

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将是值得的。