简体   繁体   中英

#copy from excel and paste to notepad using VBA

I am able to print the values from excel to notepad, but the format is bit different,

Dim txtFile As String, rng As Range, cellValue As Variant, r As Integer, c As Integer
    txtFile = slocation & "\" & "Cont_name_" & Filename & ".txt"
    lrow = Range("I" & Rows.Count).End(xlUp).Row
        Range("A2:G" & lrow).Select
        Set rng = Selection
        Open txtFile For Output As #1
        For r = 1 To rng.Rows.Count
            For c = 1 To rng.Columns.Count
                cellValue = rng.Cells(r, c).Value
                If InStr(cellValue, "/") Then
                    cellValue = Format(cellValue, "yyyyMMDD")
                End If
                If c = rng.Columns.Count Then
                    Print #1, cellValue
                Else
                    Print #1, cellValue,
                End If
            Next c
        Next r
                Close #1

Spaces are more than the requirement, please help to achieve the desired output,because the tool is accepting only the desired format示例图像

Your first output uses the standard "print zones" in every 14th column (positions 1, 15, 29, ...), which you get by printing with appended comma

.............|.............|.............|.............|.............|.............|
XXX-XX-XXXX 20190111 AA 123 NAME NAME XXXXX

Your desired output starts at the next multiple of 8 characters (1, 9, 17, ...)

.......|.......|.......|.......|.......|.......|.......|.......|.......|
XXX-XX-XXXX.....20190111........AA......123.....NAME....NAME....XXXXX

You can set the next print position in your file by Seek

Private Sub SaveAsText()
    Dim rng As Range
    Dim r As Long, c As Long

    Set rng = ActiveSheet.Range("A1:G1")

    Dim file1 As Integer
    file1 = FreeFile
    Open ThisWorkbook.Path & "\test.txt" For Output As file1

    For r = 1 To rng.Rows.Count
        For c = 1 To rng.Columns.Count
            If c = 1 Then
                Print #file1, CStr(rng.Cells(r, c).Value);
            Else
                Seek #file1, (Seek(file1) \ 8 + 1) * 8 + 1
                Print #file1, CStr(rng.Cells(r, c).Value);
            End If
        Next c
    Next r
    Close #file1

End Sub

Additional Hints:

Use Freefile to get the next free file number (which might be 1).

Use CStr() to prevent the automatically added space characters before and after numeric values.

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