如何使用vba代码打开txt文件并将其内容复制到excel?

时间:2017-10-09 08:38:19

标签: excel vba excel-vba

我需要从同一个文件夹中打开多个txt文件并将其内容复制到一个excel文件(如模板)来修改值,然后,我需要将修改后的值从excel复制到txt文件。我们怎么做这个VBA自动化?任何回复都会有所帮助。

3 个答案:

答案 0 :(得分:2)

您可以使用以下方法打开文件(found there,使其适应!)

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

使用以下方法(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

打电话给他们
OpenAndImportTxtFile
SaveFile

答案 1 :(得分:1)

答案 2 :(得分:0)

听起来您想将所有文本文件合并为一个文件。这个选项怎么样?

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