简体   繁体   中英

How to Copy and Paste Into Text File and Save Based on Column Row Data

I have a question on saving data from an Excel Sheet to a.txt file. I need to copy each cell from Column R of my Workbook and for each cell in Column R to create a.txt file, paste the data, and save it based on the same row column A data. This will create a text file for each line item in Column R and name the file based on the same row column A value. I have limited experience with VBA. Below is a sample of the data.

在此处输入图像描述

Below is some VBA that loops through all rows on a worksheet, creates a text file in the folder specified named after the data in column A, and writes the data in column R to it.

Sub sSaveData(strFolder As String)
    On Error GoTo E_Handle
    Dim strFile As String
    Dim intFile As Integer
    Dim lngLastRow As Long
    Dim lngLoop1 As Long
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")
    If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
    lngLastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    For lngLoop1 = 1 To lngLastRow
        strFile = strFolder & ws.Cells(lngLoop1, 1) & ".txt"
        intFile = FreeFile
        Open strFile For Output As intFile
        Print #intFile, ws.Cells(lngLoop1, 18)
        Close #intFile
    Next lngLoop1
sExit:
    On Error Resume Next
    Set ws = Nothing
    Reset
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & "sSaveData", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub

Regards,

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