0

As highlighted in the title, I would like a macro to import a .txt file rapidly. I've already tried multiple code but everytime you have to open, then copy then close the .txt file and since I have a couple of .txt files it takes somes times:

Sub ImportChange()
ChDir "R:\Desktop\Hugo"
SendKeys "~"
Workbooks.OpenText Filename:="R:\Desktop\Hugo.txt", 
DataType:=xlDelimited, semicolon:=True
Cells.Select
Selection.Copy
Windows("Tableau.xlsm").Activate
Sheets("Change").Select
Cells.Select
ActiveSheet.Paste
Columns("B:B").Select
Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False
Columns("A:A").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
Range("A1").Select
Windows("Hugo.txt").Activate
Application.CutCopyMode = False
ActiveWorkbook.Close
SendKeys "~"
End Sub 

Thus my question is can I import using SQL instead of VBA or can I just import a .txt file without opening then closing it?

1
  • You left out the critical bit. Please amend your post to include a description of the structure of your text file, or provide an example. Commented Apr 12, 2022 at 9:55

1 Answer 1

1

You can just use Bulkinsert to import directly your file to SQL. Once you have it on the database, you only have to load it on Excel once

---- INSERT
        bulk insert [TABLE]
        from 'c:\Filepath.txt'
        with
        (
        firstrow = 2,
        fieldterminator = '\t',
        rowterminator = '\n',
        maxerrors = 0
        )
---- MOVE
        EXEC master..xp_cmdshell 'MOVE filepathfrom.txt filepathTO.txt'

---- RENAME
        DECLARE @Rename VARCHAR(100)
        SET @Rename = 'RENAME "OriginalFilePath.txt" ' + @FilenameRenamed
        EXEC master..xp_cmdshell @Rename
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.