简体   繁体   中英

Word VBA: Table cell range to text file

I'd like to copy a table like this in a word document and extract only the track titles and composers. The selecting of the range goes according to plan:

Dim myCells As Range
With ActiveDocument
    Set myCells = .Range(Start:=.Tables(1).Cell(2, 3).Range.Start, _
        End:=.Tables(1).Cell(.Tables(1).Rows.Count, 3).Range.End)
    myCells.Select
End With

Now, when I copy this selection manually and paste it into notepad, I get exactly what I want:

Title
Composer
Title
Composer
etc.

However, I want to write this selection automatically into a text file. When I try to do this, all content is stuffed in one line of text and little squares (paragraph signs?) pop up everywhere.

How would be I be able to get the result of the manual copying, using VBA?

Try this

Sub Allmusic()
    Dim filesize As Integer
    Dim FlName As String, tempStr As String
    Dim i As Long
    Dim MyAr() As String

    '~~> Name of Output File
    FlName = "C:\Sample.Txt"

    '~~> Get a free file handle
    filesize = FreeFile()

    '~~> Open your file
    Open FlName For Output As #filesize

    With ActiveDocument
        For i = 2 To .Tables(1).Rows.Count

            '~~> THIS LINE WILL NOT REFLECT CORRECTLY IN THE BROWSER
            '~~> PLEASE REFER TO THE SCREENSHOT OR THE ATTACHED FILE
            tempStr = Replace(.Tables(1).Cell(i, 3).Range.Text, "", "")

            If InStr(1, tempStr, Chr(13)) Then
                MyAr = Split(tempStr, Chr(13))
                Print #filesize, MyAr(0)
                Print #filesize, MyAr(1)
            Else
                Print #filesize, tempStr
            End If
            Print #filesize, ""
        Next i
    End With

    Close #filesize
End Sub

SNAPSHOT

在此输入图像描述

SAMPLE FILE

http://sdrv.ms/Mo7Xel

Download the file and run the procedure Sub Allmusic()

OUTPUT

在此输入图像描述

HTH

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