日期:2014-05-16  浏览次数:20459 次

VBS操作文件 数据库
文本文件的读取
Option Explicit

Const ForReading = 1

Const ForWritting = 2

Const ForAppending = 8

Dim fso,file,msg

Set fso=CreateObject("Scripting.FileSystemObject")

Set file=fso.OpenTextFile("d:\a.txt",ForReading,True)

Do While Not file.AtEndOfStream

msg = file.ReadLine

MsgBox msg

Loop

file.Close

Set file=Nothing

Set fso=Nothing

第一步:首先创建两个对象,一个FileSystemObject对象fso,然后用fso对象的opentextfile方法去打开一个文件。并返回一个textStream对象给file。

第二步:使用file对象对打开的文件进行操作,例子中是对文件的读取。读取通过file对象的一个方法ReadLine来实现。

第三步:读取完毕,关闭文件

第四步:释放file对象和fso对象

File还有一些其它的方法,如Read、ReadAll等

文本文件的写入
Option Explicit

Const ForReading = 1

Const ForWritting = 2

Const ForAppending = 8

Dim fso,file,msg

Set fso=CreateObject("Scripting.FileSystemObject")

Set file=fso.OpenTextFile("d:\a.txt",ForWritting,True)

File.WriteLine “hello world”

File.WriteLine “this is a writing file case”

file.Close

Set file=Nothing

Set fso=Nothing

文件写入的步骤跟读取是一样的,唯一的区别是它们打开文件的方式不同。一个是以读的方式打开,另一个是以写的方式,这通过OpenTextFile方法的参数实现。OpenTextFile方法的第二个参数是一个常量值:1、2、8,1是ForReading的,2是ForWritting的,3是ForAppending的追加方式。

Excel文件的读写


Option Explicit

Dim xlApp,xlFile,xlSheet,xlSheet2

Dim iRowCount,iLoop,jLoop,numAdd(4),iColumnCount,record

Set xlApp=CreateObject("Excel.Application")

Set xlFile=xlApp.Workbooks.Open("D:\data.xls")

Set xlSheet=xlFile.Sheets("Sheet1")

Set xlSheet2=xlFile.Sheets("Sheet2")



iRowCount=xlSheet.usedRange.Rows.Count

iColumnCount=xlSheet.usedRange.Columns.Count



For iLoop = 1 To iRowCount

      For jLoop = 1 To iColumnCount

             numAdd(jLoop) = xlSheet.Cells(iLoop,jLoop)

             'MsgBox numAdd(jLoop)

             xlSheet2.Cells(iLoop,jLoop)=numAdd(jLoop)

            

             'MsgBox xlSheet2.Cells(iLoop,jLoop)

      Next

      record = Join(numAdd," ")

      MsgBox record

Next



xlFile.Save

xlFile.Close

xlApp.Quit

Set xlSheet = Nothing

Set xlSheet2 = Nothing

Set xlFile = Nothing

Set xlApp = Nothing

第一步:Excel的三层概念:Application、ExcelFile、Sheet,因此需要创建三个对象来实现对Excel文件的操作。首先创建一个Excel.Application对象xlApp,然后通过xlApp打开一个Excel文件,并返回一个对象给xlFile,最后通过xlFile的Sheets属性来操作某一个sheet。

第二步:通过sheet对象的cells子对象来操作某一sheet中的区域,sheet对象可以通过usedRange属性来识别此文件已经使用的cells。通过其中的count方法来获取具体值。

第三步:操作完成,保存文件、关闭文件、退出程序

第四步:释放对象

数据库的读写
Dim Cnn, Rst, strCnn

Set Cnn = CreateObject( "ADODB.Connection“ )

Set Rst = CreateObject( "ADODB.Recordset“ )

strCnn= "Provider=Microsoft.Jet.OLEDB.4.0.1;Data Source=C:\qtp_file\cal.mdb; Persist Security Info=False"

Cnn.Open strCnn

Rst.Open "Select * from student", Cnn

Rst.MoveFirst

Do While Not Rst.EOF

MsgBox Trim(Rst.Fields("name"))

Rst.MoveNext

Loop

Rst.Close

Cnn.Close

Set Rst = Nothing

Set Cnn = Nothing

1) 创建两个对象Connection对象和RecordSet对象和一个字符串连接串

2) 使用Connection通过连接串连接数