• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 512
  • Last Modified:

VBA Create and Rename excel tabs


I want to import some text files programmatically and rename them according to their original file name.

I think my code should work, but the tab names are still "sheet 1" and so forth

I used the macro recorder to generate the code to insert tab

strFile = Dir(strPath & "\*.dat")
Do While Len(strFile) > 0
strPathFile = strPath & "\" & strFile

Sheets.Add after:=Sheets(Sheets.Count)

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & strPathFile _
        , Destination:=Range("$A$1"))
        iNameLen = Len(strFile)
        .Name = strFile '<------I try to change the tab name here, but it's not working. 
        .FieldNames = False
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

strFile = Dir()

Open in new window

1 Solution
you could say

activesheet.name = strfile

at the end after the 'End with'
TheDetectiveAuthor Commented:
Thanks, that worked. I can't believe the answer is so simple. Cheers
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now