QTP基本使用——WORD

时间:2022-05-13 06:22:35

1. '创建word的对象
Set oWordApp = CreateObject("Word.Application") '此处亦可使用Excel.Application

'将word对象设置为可见
oWordApp.Visible = True

'关闭word对象
oWordApp.Quit

'对象清空
Set oWordApp = Nothing

2. 创建文档
Set oWordApp = CreateObject("Word.Application")

oWordApp.Visible = True

'增加一个新文档
Set oWordDoc = oWordApp.Documents.Add

'另存为testbbk.doc
'问题:为什么不直接save, 而用saveas呢
oWordDoc.SaveAs "d:/testbbk.doc"
msgbox "文件创建成功!"

oWordDoc.Close

oWordApp.Quit

Set oWordDoc = Nothing
Set oWordApp = Nothing

3. '打开一个已经存在的文档
Set oWordDoc = GetObject("d:/testbbk.doc")

Set oWordApp = oWordDoc.Application

oWordApp.Visible =True

msgbox "打开这个文档, 请检查"

'理论上应该先退出Doc, 然后再退出程序的,但是在这里确实相反的, 有待于研究
oWordDoc.Close

oWordApp.Quit

Set oWordDoc = Nothing
Set oWordApp = Nothing


4, 打开文档的另外一种方法
Set oWordApp = CreateObject("Word.Application")

oWordApp.Visible = True

'打开一个已知的文件

Set oWordDoc = oWordApp.Documents.Open("d:/testbbk.doc")

msgbox "打开这个文档, 请检查"


5:‘向一个文档中插入表格
EditWord "d:/testbbk.doc"

Function EditWord(filepath)

    Set oWordApp = CreateObject("Word.application")
    oWordApp.visible = True
    Set oWordDoc = oWordApp.Documents.Open(filepath)
    oWordDoc.Range.Select
    Set oWordSet = oWordApp.Selection
    With oWordSet
        Set oNewTable = .Tables.Add(.range, 5, 3)
        oNewTable.Range.Font.size = 8
        i = 1
        oNewTable.Cell(i, 1).Range.Text = "i"
        oNewTable.Cell(i, 2).Range.Text = "i*2"
        oNewTable.Cell(i, 3).Range.Text = "i*3"

        For i =2 to 5
             oNewTable.Cell(i, 1).Range.Text = i-1
             oNewTable.Cell(i, 2).Range.Text = (i-1)*2
             oNewTable.Cell(i, 3).Range.Text = (i-1)*3
        Next
             oNewTable.Rows.Add
             i = oNewTable.Rows.Count
              oNewTable.Cell(i, 1).Range.Text = i-1
             oNewTable.Cell(i, 2).Range.Text = (i-1)*2
             oNewTable.Cell(i, 3).Range.Text = (i-1)*3
       
    End with

   end function


6: ’向word中插入图片

EditWord "d:/testbbk.doc","d:/test.bmp"

Function EditWord(filepath, filepic)

    Set oWordApp = CreateObject("Word.application")
    oWordApp.visible = True
    Set oWordDoc = oWordApp.Documents.Open(filepic)
    oWordDoc.Range.Select
    Set oWordSet = oWordApp.Selection
    With oWordSet
        Set oImg = .InlineShapes.AddPicture(filepic, False, True)
        oImg.Width = oImg.Width*0.50
        oImg.Height = oImg.Height*0.50
        '中间对齐
        oImg.Range.ParagraphFormat.Alignment = 1
        .TypeParagraph
        .TypeText "qtp学习之对word的基本操作"
        .TypeParagraph
   
    End with
   
   end function

7. ‘向word中插入文本

EditWord "C:/testbbo.doc", "QTP学习之word"
Function EditWord(filepath, content)
    Set oWordApp = CreateObject(Word.Application)
    oWordApp.Visible = True
    Set doc = oWordApp.Documents.Open(filepath)
    doc.Content = content
    doc.save
    Set doc = Nothing
    Set oWordApp = Nothing
    ReadWord = True

End Function

PS: 基本上分为三步走, 第一打开对象, 第二创建或者打开实例, 第三修改或者保存实例