简体   繁体   中英

How to open a txt file with vba code and and copy its contents to excel?

I need to open multiple txt files from same folder and copy its contents to a single excel file (like a template) to modify the values and then, I need to copy the modified values from excel to txt files. How can we do this VBA automation? any reply would be helpful.

You can open a file by using the following method ( found there , adapt it!)

Sub OpenAndImportTxtFile()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("path and name of your file")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

And export your sheet with the following method ( found there )

Sub SaveFile()
Dim ans As Long
Dim sSaveAsFilePath As String

On Error GoTo ErrHandler:

sSaveAsFilePath = "path and name of your file"

If Dir(sSaveAsFilePath) <> "" Then
    ans = MsgBox("File " & sSaveAsFilePath & " exists.  Overwrite?", vbYesNo + vbExclamation)
    If ans <> vbYes Then
        Exit Sub
    Else
        Kill sSaveAsFilePath
    End If
End If

Sheet1.Copy '//Copy sheet to new workbook
ActiveWorkbook.SaveAs sSaveAsFilePath, xlTextWindows '//Save as text (tab delimited) file

If ActiveWorkbook.Name <> ThisWorkbook.Name Then '//Double sure we don't close this workbook
    ActiveWorkbook.Close False
End If

My_Exit:
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume My_Exit
End Sub

Call them with

OpenAndImportTxtFile
SaveFile

There are pretty good guides I used to do the same work like you.

For Text to Excel:

http://www.excel-easy.com/vba/examples/read-data-from-text-file.html

vba: Importing text file into excel sheet

For Excel to Text:

http://www.excel-easy.com/vba/examples/write-data-to-text-file.html

Good luck

It sounds like you want to merge all text files into one single file. How about this option?

Sub CombineTextFiles()
    Dim lFile As Long
    Dim sFile As String
    Dim vNewFile As Variant
    Dim sPath As String
    Dim sTxt As String
    Dim sLine As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show Then
            sPath = .SelectedItems(1)
            If Right(sPath, 1) <> Application.PathSeparator Then
                sPath = sPath & Application.PathSeparator
            End If
        Else
             'Path cancelled, exit
            Exit Sub
        End If
    End With
    vNewFile = Application.GetSaveAsFilename("CombinedFile.txt", "Text files (*.txt), *.txt", , "Please enter the combined filename.")
    If TypeName(vNewFile) = "Boolean" Then Exit Sub
    sFile = Dir(sPath & "*.txt")
    Do While Len(sFile) > 0
        lFile = FreeFile
        Open CStr(sFile) For Input As #lFile
        Do Until EOF(lFile)
            Line Input #1, sLine
            sTxt = sTxt & vbNewLine & sLine
        Loop
        Close lFile
        sFile = Dir()
    Loop
    lFile = FreeFile
    Open CStr(vNewFile) For Output As #lFile
    Print #lFile, sTxt
    Close lFile
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM