Results 1 to 3 of 3

Thread: copy and rename sheet

Hybrid View

  1. #1
    Frenzied Member
    Join Date
    Mar 05
    Posts
    1,074

    copy and rename sheet

    I have this Var1="0001"
    I need to check if in active workbook exists the sheet named "0001" if not exists copy the sheet SERVICE and rename it with the value of var, in this case "0001"

  2. #2
    PowerPoster
    Join Date
    Dec 04
    Posts
    18,526

    Re: copy and rename sheet

    try like
    Code:
    fnd = false
    for each sht in thisworkbook.sheets
      if sht.name = var1 then fnd = true: exit for
    next
    if not fnd then
      sheets("service").copy before:=sheets(1)
      sheets(1).name = var1
    end if
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  3. #3
    Super Moderator koolsid's Avatar
    Join Date
    Feb 05
    Location
    Mumbai, India
    Posts
    11,415

    Re: copy and rename sheet

    A slightly faster method.

    Code:
    Sub Sample()
        Dim Var1 As String
        Dim ws As Worksheet
        
        Var1 = "0001"
        
        On Error Resume Next
        Set ws = Sheets(Var1)
        On Error GoTo 0
        
        If ws Is Nothing Then
            Sheets("service").Copy Before:=Sheets(1)
            ActiveSheet.Name = Var1
        End If
    End Sub
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved

    Microsoft MVP: 2011 - Till Date IMP Links : Acceptable Use Policy, FAQ

    MyGear:
    Sony VGN-FZ27G with a triple boot between (XP+Office 2003+VB6), (VISTA+Office 2007+VS2008) and (Win7+Office 2010+VS2010) || Sony VPCCB-45FN with a Win7+Office 2010+VS2010. VM: (XP+Office 2003+VB6), (VISTA+Office 2007+VS2008), (Win8+Office 2010+VS2012) || Mac Book Pro (10.6.8) with Office 2011

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •