Read and write into a file using VBScript

前端 未结 9 1366
轮回少年
轮回少年 2020-11-27 06:34

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-

Set         


        
相关标签:
9条回答
  • 2020-11-27 07:16

    This is for create a text file

    For i = 1 to 10
        createFile( i )
    Next
    
    Public Sub createFile(a)
    
        Dim fso,MyFile
        filePath = "C:\file_name" & a & ".txt"
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set MyFile = fso.CreateTextFile(filePath)
        MyFile.WriteLine("This is a separate file")
        MyFile.close
    
    End Sub
    

    And this for read a text file

    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set dict = CreateObject("Scripting.Dictionary")
    Set file = fso.OpenTextFile ("test.txt", 1)
    row = 0
    Do Until file.AtEndOfStream
      line = file.Readline
      dict.Add row, line
      row = row + 1
    Loop
    
    file.Close
    
    For Each line in dict.Items
      WScript.Echo line
      WScript.Sleep 1000
    Next
    
    0 讨论(0)
  • 2020-11-27 07:18

    Below is some simple code to execute this:

    sLocation = "D:\Excel-Fso.xls"
    sTxtLocation = "D:\Excel-Fso.txt"
    Set ObjExl = CreateObject("Excel.Application")
    Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
    Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
    ObjExl.Visible = True
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FSOFile = FSO.CreateTextFile (sTxtLocation)
    sRowCnt = ObjWrkSht.usedRange.Rows.Count
    sColCnt = ObjWrkSht.usedRange.Columns.Count
    For iLoop = 1 to sRowCnt
      For jLoop = 1 to sColCnt 
        FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab 
      Next
    Next
    
    Set ObjWrkBk = Nothing
    Set ObjWrkSht = Nothing
    Set ObjExl = Nothing
    Set FSO = Nothing
    Set FSOFile = Nothing
    
    0 讨论(0)
  • 2020-11-27 07:24

    You could open two textstreams, one for reading

    Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
    

    and one for appending

    Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
    

    The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

    0 讨论(0)
提交回复
热议问题