Question

Ce code va lire une ligne d'un fichier texte:

set file = CreateObject("Scripting.FileSystemObject").OpenTextFile("c:\number.txt", 1)
text = file.ReadLine
MsgBox text

Comment puis-je faire lire à plusieurs reprises une ligne après l'autre à partir du même fichier? Je suppose que je devrais utiliser une boucle ici, à droite? J'ai besoin pour lire la première ligne du fichier lors de la première itération, la deuxième ligne à la deuxième itération, le troisième au troisième et ainsi de suite jusqu'à ce que toutes les lignes ont été lues. Comment puis-je faire?

Ajout important: j'ai besoin du code pour fonctionner sur chaque ligne un par un - pas tout à la fois

Était-ce utile?

La solution

Utilisez la méthode ReadAll():

text = file.ReadAll

(cela peut intéresser: FileSystemObject Exemple de code )

Avec une boucle:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine

Set fso = CreateObject("Scripting.FileSystemObject")

FileName = "c:\testfile.txt"

Set MyFile = fso.OpenTextFile(FileName, ForReading)

'' Read from the file
Do While MyFile.AtEndOfStream <> True
    TextLine = MyFile.ReadLine

    '' Do stuff to TextLine

Loop
MyFile.Close

Autres conseils

Si pour une raison quelconque vous voulez utiliser les routines de gestion des fichiers VBA en construction, vous pouvez utiliser le code comme ceci:

Sub ReadAFileLineByLine()
    Dim InStream As Integer
    InStream = FreeFile()
    Open "C:/tmp/fastsynchtoquesttry_quest.txt" For Input As InStream

    Dim CurrLine As String
    Do While True
        Line Input #InStream, CurrLine
        ' do stuff to CurrLine
        If EOF(InStream) Then Exit Do
    Loop

    Close #InStream
End Sub

Vous pouvez ajouter une référence * au modèle d'objet Windows Script Host, il vous aidera avec l'objet FileSystemObject, parce que vous pouvez dire:

Dim fs As FileSystemObject
Dim f As TextStream

Ce qui vous permettra d'utiliser IntelliSense pour voir les différentes propriétés et l'Explorateur d'objets pour explorer la bibliothèque.

* Dans la fenêtre de code, choisissez Outils, références et cochez la case à côté de la bibliothèque que vous voulez.

J'ai écrit une routine VBA qui lit un fichier texte et insérer une nouvelle diapositive pour chaque phrase dans le texte.

Tout d'abord, à la diapositive n ° 1, ajouter un bouton qui appelle la macro appelée « générer »

Le code source passe:

Const DEFAULT_SLIDE = 1 ' the slide to copy the layout style from
Const MARGIN = 50       ' margin of the generated textbox

Sub generate()
    Dim txtFile As String   ' text file name
    Dim fileNo As Integer   ' file handle
    Dim buffer As String    ' temporary string buffer
    Dim sentence() As String    ' the main array to save sentences
    Dim i, total As Integer
    Dim myLayout As CustomLayout
    Dim mySlide As Slide
    Dim myShape As Shape
    Dim myWidth, myHeight As Integer    'slide width and height


    txtFile = "text2sample.txt"
    txtFile = ActivePresentation.Path & "\" & txtFile   'textfile should be in the same Dir as this ppt

    If Len(Dir$(txtFile)) = 0 Then
        MsgBox txtFile & " file not found."
        Exit Sub
    End If

    'Initialize array
    ReDim sentence(0)

    'get file handle number
    fileNo = FreeFile()
    Open txtFile For Input As #fileNo

    i = 0
    Do While Not EOF(fileNo)
        Line Input #fileNo, buffer  'read & save sentences line by line
        ReDim Preserve sentence(i + 1)  ' increase 1 more array
        sentence(i) = LTrim(RTrim(buffer))
        i = i + 1
    Loop
    Close #fileNo

    total = i
    Randomize   ' for random color

    With ActivePresentation.PageSetup
        myWidth = .SlideWidth - MARGIN  'get width and height
        myHeight = .SlideHeight - MARGIN
    End With

    For i = 0 To total
        Set myLayout = ActivePresentation.Slides(DEFAULT_SLIDE).CustomLayout
        'add a slide like slide #1
        Set mySlide = ActivePresentation.Slides.AddSlide(DEFAULT_SLIDE + 1 + i, myLayout)
        'add a textbox with margin
        Set myShape = ActivePresentation.Slides(DEFAULT_SLIDE + 1 + i).Shapes. _
        AddTextbox(msoTextOrientationHorizontal, MARGIN, MARGIN, myWidth, myHeight)
        With myShape
            'add a sentence
            .TextFrame.TextRange.Text = sentence(i)
            .TextFrame.TextRange.Font.Size = 60
            ' color 255 is too bright. Pick a less bright color (200)
            .TextFrame.TextRange.Font.Color.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
            .TextFrame.TextRange.Font.Bold = msoTrue
            .TextFrame.TextRange.Font.Shadow = msoTrue
            ' If you want to change the color of the shape
            '.Fill.ForeColor.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
            '.Fill.BackColor.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
            '.Fill.Solid
        End With
        'add a textbox for slideshow progress ex) 1/100
        Set myShape = ActivePresentation.Slides(DEFAULT_SLIDE + 1 + i).Shapes. _
        AddTextbox(msoTextOrientationHorizontal, 0, 0, 150, 20)
        With myShape
            .TextFrame.TextRange.Text = "( " & i & " /" & total & " )"
            .TextFrame.TextRange.Font.Size = 20
            .TextFrame.TextRange.Font.Color.RGB = RGB(100, 100, 100)
        End With
    Next

    MsgBox total & " Slides were added.", vbInformation

End Sub

Télécharger le fichier: http://konahn.tistory.com/attachment/cfile8.uf@2175154C573D3BC02A2DFA.pptm

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top