注册 登录
编程论坛 VB6论坛

VB如何读取word中表格第一列、第二列内容?

xingming022 发布于 2019-05-24 15:56, 2710 次点击
VB如何读取word中表格第一列、第二列内容?

6 回复
#2
wufuzhang2019-05-24 21:00
回复 楼主 xingming022
程序代码:

Option Explicit

Dim str1 As String
Dim str2 As String

Private Sub Command1_Click()
  Dim myword As Object, mydocument As Object, mytable As Object
  Set myword = CreateObject("Word.Application") '创建word对象
  myword.Visible = True
  Set mydocument = myword.Documents.Open(App.Path & "\123.docx")
  
  Dim i As Byte
  Dim j As Byte
  For i = 1 To mydocument.Tables.Count
      Set mytable = mydocument.Tables(i)
      For j = 1 To mytable.Rows.Count
          str1 = mytable.Cell(j, 1).Range
          str1 = Left(str1, Len(str1) - 2)
          Print str1
          str2 = mytable.Cell(j, 2).Range
          str2 = Left(str2, Len(str2) - 2)
          Print str2
      Next
  Next
End Sub

窗体添加一个命令按钮,AutoRedraw属性为True
#3
xingming0222019-05-25 20:48
回复 2楼 wufuzhang
非常感谢,如果是123.doc  这个文件已经打开了该怎么操作?
#4
wufuzhang2019-05-25 23:56
回复 3楼 xingming022
程序代码:

Option Explicit

Dim str1 As String
Dim str2 As String

Private Sub Command1_Click()
On Error Resume Next
  Dim k As Integer
  Dim filepath As String
  Dim myword As Object, mydocument As Object, mytable As Object
  
  
  filepath = App.Path & "\123.docx"
  If Dir(filepath) <> "" Then
     Name filepath As App.Path & "\1232.docx"
  End If
  If Err.Number <> 0 Then
     Print "文件打开了"
     Set myword = GetObject(, "Word.Application")
     For Each mydocument In myword.documents
         k = k + 1
         If mydocument.FullName = filepath Then
            Exit For
         End If
     Next
     Set mydocument = myword.documents(k)
  Else
     Print "文件没打开"
     Name App.Path & "\1232.docx" As filepath
     Set myword = CreateObject("Word.Application") '创建word对象
     myword.Visible = True
     Set mydocument = myword.documents.Open(filepath)
  End If
  

 
  
  Dim i As Byte
  Dim j As Byte
  For i = 1 To mydocument.Tables.Count
      Set mytable = mydocument.Tables(i)
      For j = 1 To mytable.Rows.Count
          str1 = mytable.Cell(j, 1).Range
          str1 = Left(str1, Len(str1) - 2)
          Print str1
          str2 = mytable.Cell(j, 2).Range
          str2 = Left(str2, Len(str2) - 2)
          Print str2
      Next
  Next
End Sub


代码修改了一下,先判断文件是否已打开,再读取表格中内容。
#5
xingming0222019-05-26 12:05
回复 4楼 wufuzhang
非常感谢。
#6
xingming0222019-05-26 22:19
回复 4楼 wufuzhang
我最近的帖子都是您帮忙解决了,想请教下,您怎么练就成一看就会的功夫的?您是职业做编程的?
#7
wufuzhang2019-05-27 00:02
回复 6楼 xingming022
过奖了,我也是尝试后才找到解决问题的办法。
公司项目有问题都是我来解决,遇到的问题多了,
自然有自己查找问题的一套思路了。
1