完整代码:
Dim wdApp As Word.Application
Dim exApp As Excel.Application
Private Sub Command1_Click()
If Len(Text1.Text) < 1 Then MsgBox "请选择word文档": Exit Sub
If Len(Text2.Text) < 1 Then MsgBox "请选择excel文档": Exit Sub
Set wdApp = New Word.Application
Set exApp = New Excel.Application
wdApp.Visible = True
exApp.Visible = True
xx = wdApp.Documents.Open(Text1.Text)
exApp.Workbooks.Open Text2.Text
For k = 1 To exApp.WorksheetFunction.CountA(exApp.ActiveWorkbook.Sheets(1).Range("a:a"))
s_txt = Range("a" & k)
For i = 1 To wdApp.ActiveDocument.Tables.Count
For j = 1 To wdApp.ActiveDocument.Tables(i).Rows.Count
wdApp.ActiveDocument.Tables(i).Cell(j, 1).Select
If Left(wdApp.Selection.Text, Len(wdApp.Selection) - 2) = s_txt Then
wdApp.ActiveDocument.Tables(i).Cell(j, 2).Select
exApp.ActiveWorkbook.Sheets(1).Range("b" & k) = Left(wdApp.Selection.Text, Len(wdApp.Selection.Text) - 2)
End If
Next
Next
Next
wdApp.Quit (False)
exApp.ActiveWorkbook.Save
exApp.Quit
MsgBox "取值完成!"
End Sub
Private Sub Command2_Click()
CommonDialog1.Filter = "Word文档(*.doc)|*.doc"
CommonDialog1.ShowOpen
If Len(CommonDialog1.FileName) > 1 Then Text1.Text = CommonDialog1.FileName
End Sub
Private Sub Command3_Click()
CommonDialog1.Filter = "Excel文档(*.xls)|*.xls"
CommonDialog1.ShowOpen
If Len(CommonDialog1.FileName) > 1 Then Text2.Text = CommonDialog1.FileName
End Sub
Private Sub Form_Load()
Text1.Text = ""
Text2.Text = ""
End Sub
读取WORD表格中的内容:
wdApp.Documents.Open "E:\Lixin\Share\word\baogao\aaa.doc"
For i = 1 To wdApp.ActiveDocument.Tables(1).Rows.Count
wdApp.ActiveDocument.Tables(1).Cell(i, 1).Select
If Left(wdApp.ActiveDocument.Selection.Text, Len(wdApp.ActiveDocument.Selection.Text) - 2) = "铅笔" Then
wdApp.ActiveDocument.Tables(1).Cell(i, 2).Select
MsgBox Left(wdApp.ActiveDocument.Selection.Text, Len(wdApp.ActiveDocument.Selection.Text) - 2)
End If
Next