VB修改Word中的表格元素

工作中遇到了这个问题,技术难度虽然不太大,但是为了方便,写了两个函数,先发上来,供大家以后参考,自己也做个记录。

  1.     Dim objWordApp As New Word.Application
  2.     Dim objWordDoc As New Word.Document
  3.     objWordApp.Documents.Open strFileName
  4.     Set objWordDoc = objWordApp.ActiveDocument    
  5.     '//
  6.     '新增操作表格的项
  7.     '在使用前,要先在模板中插入一个临时表格
  8.     '如果表格的行或列不够,系统会自动新增
  9.     '但新增的表格可能会不太规范,所以最好在模板中就先定义好表格的各项数据(宽度,大小,字体...)
  10.     WriteTable objWordDoc, 1, 1, "列头1", 1
  11.     WriteTable objWordDoc, 1, 2, "列头2", 1
  12.     WriteTable objWordDoc, 1, 3, "列头3", 1
  13.     WriteTable objWordDoc, 1, 4, "列头4", 1
  14.     WriteTable objWordDoc, 1, 5, "列头5", 1
  15.     WriteTable objWordDoc, 2, 1, "列值A", 1
  16.     WriteTable objWordDoc, 2, 2, "列值B", 1
  17.     WriteTable objWordDoc, 2, 3, "列值C", 1
  18.     WriteTable objWordDoc, 2, 4, "列值D", 1
  19.     WriteTable objWordDoc, 2, 5, "列值E", 1
  20.     '//
  21.    objWordApp.Visible = True
  22.    objWordDoc.PrintOut
  23.    objWordDoc.Close
  24.    objWordApp.Quit

 

'// 然后是两个操作表格的函数,函数虽然简单,但提示一个方向,一个思路.

'/// 检查当前表格行或列的总数是否足够,不够则会新增
'/// objDoc Word文档对象
'/// iRows  需要的行数
'/// iCols  需要的列数
'/// iTables 要操作文档中的第几个表格, 1 - N, 默认为第一个
Private Function InsertTable(objDoc As Word.Document, iRows As Integer, iCols As Integer, Optional ByVal iTables As Integer = 1)
    Dim countRows As Integer
    Dim countCols As Integer
    Dim TableIndex As Integer
    Dim i As Integer
   
    TableIndex = iTables
    If TableIndex > 0 Then
        countCols = objDoc.Tables(TableIndex).Columns.Count
        countRows = objDoc.Tables(TableIndex).Rows.Count
        For i = countCols To iCols - 1
            objDoc.Tables(TableIndex).Columns.Add
        Next
        For i = countRows To iRows - 1
            objDoc.Tables(TableIndex).Rows.Add
        Next
    End If
   
End Function

 

'/// 在指定文档中的指定表格中的指定行列中插入值
'/// objDoc Word文档对象
'/// iRows  指定的行数
'/// iCols  指定的列数
'/// sValue 要插入的值
'/// iTables 要操作文档中的第几个表格, 1 - N , 默认为第一个
Private Function WriteTable(objDoc As Word.Document, iRows As Integer, iCols As Integer, sValue As String, Optional ByVal iTables As Integer = 1)
    Dim TableIndex As Integer
    TableIndex = iTables
    If TableIndex > 0 Then
        InsertTable objDoc, iRows, iCols, iTables
        objDoc.Tables(TableIndex).Cell(iRows, iCols).WordWrap = True
        objDoc.Tables(TableIndex).Cell(iRows, iCols).Range.Text = sValue
    End If
End Function

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值