VB操作word总结
- 格式:doc
- 大小:94.50 KB
- 文档页数:18
vb操作(cāozuò)word详解vb操作(cāozuò)word详解vb操作(cāozuò)word详解Visual Basic支持一个对象集合,该集合中的对象直接对应于Microsoft Word 97中的元素,并且通过用户界面,用户熟悉这些元素中的绝大多数。
例如,Document 对象代表了一个打开的文档,Bookmark对象代表了一个文档中的书签,而Selection对象则代表了在一个文档窗口窗格(chuānɡ ɡé)中的选定内容。
在Word中,每一类元素-文档、表格、段落、书签、域等等-都可以用Visual Basic的对象来表示。
要在Word中自动执行任务,可以使用这些对象的方法和属性。
关于理解和使用Microsoft Office 97对象模型的一般性内容,请参阅本书的第二章“理解对象模型”。
在Microsoft Office 97中的对象模型相当丰富(fēngfù),其中包含了大约180个对象。
要查看Word对象模型的层次关系图,请参阅“帮助”中的“Microsoft Word 对象”。
要获得对某种特定对象的详细描述,可以在此图中单击该对象的名字,或是在“帮助”的索引中对特定对象进行搜索。
怎样(zěnyàng)显示Word Visual Basic帮助要使用Word Visual Basic帮助,必须在安装过程中选择“自定义”的安装方式,并且为Word选中“Visual Basic在线(zàixiàn)帮助”复选框。
否则,安装程序不会安装Visual Basic帮助。
如果用户已经安装好了Word,那么可以再次运行Setup程序来安装Visual Basic帮助。
要查看Word Visual Basic 帮助,可以在“Visual Basic 编辑器里的“帮助”菜单中点击“目录和索引(suǒyǐn)”一项。
vbaword基本操作(经典)一.方法:Word打开方法时调用的方法:Document_Open()Word关闭时调用的方法:Document_Close()调用subInt过程:Call subIntFunction fun() As Integer‘代码Fun=1End Function调用fun函数:在其他调用的方法或函数中直接用函数(因为函数要返回一个值),比如:if(fun=1)then….end if1.1操作文件:Private Sub deleteXML()‘判断文件是否存在,然后删除文件If Dir(ThisDocument.Path + "/" + filename1) <> "" ThenKill (ThisDocument.Path + "/" + filename1) ‘End IfEnd SubPrivate Sub rename()‘重命名文件If Dir(ThisDocument.Path + "/" + "temp.xml") <> "" ThenName ThisDocument.Path & "/" & "temp.xml" As ThisDocument.Path & "/" & filename1End IfEnd Sub‘取得同目录下文件的名字Private Sub HX_FileName()Dim fso As Object, folder As Object, subfolder As Object, objFile As Scripting.file '创建FSO对象Set fso = CreateObject("scripting.filesystemobject")Set folder = fso.GetFolder(Path)For Each objFile In folder.FilesIf Strings.Right(, 8) = "gplx.xml" And Len() > 8 Then filename1 = NextEnd Sub二.声明变量Dim a as IntegerPublic mybut As CommandBarButtonPublic mybar As CommandBar三.常用语句1.If(a=1) thenElseEnd if2.do while a<26Loop3. For ID = 0 To count - 1 Step 1pidtemp = “123”exit for ‘如果要跳出for语句,就加上此句Next ID四:字符串字符串的替换:将textbox1中的内容的回车和换行都替换为空。
ItIE.Bookmarks("mm").Ra nge.l nsertAfter " name"'在WORD 指定位置(标签)写入文本,指定位置指 WORDDim MyWord As Word.A ppi ication Dim MyWordBook As Word.Docume nt模版'MyWord = CreateObject("Word.A ppi icatio n")'MyWord.Visible = False'MyWord.ActiveDocume nt.SaveAs ("test1.doc")With MyWordBook!E一!E 除.Paragraphs(.Paragraphs.Count)贝U 表示所有行iiI ■iEit,■!E.Conten t.I nsertAfter "hello" & vbCrLf'向WORD 写入一行文字并回车.Co nte nt.l nsertAfter "hello".P aragra phs (.P aragra phs.Co un t).Ra nge.F on t.Size = 10.Co nte nt.l nsertAfter "hello"利用VB 操作WORD的基本方法I E !E !E I E,■!ESet MyWord = New Word.A ppi ication,■!ESet MyWordBook = MyWord.Docume nts.Add(Model Path & "test.dot")' 打开test.dot 用户自定义的 WORD!E■ I!'MyWord.Docume nts.O pen ("test.doc")'MyWord.ActiveDocume nt.Bookmarks .I tem("MM").Select!E■ I£i'MyWord.Selectio n.Text =" 从资料库取出的相应资料"I E■ I!EMyWordBook.ActivateIt '.P aragra phs(.P aragra phs.Co un t).Ra nge.F on t.Size = 30 '设置文字字体大小(其它设置类推)如果去P aragra phs(.P aragra phs.Co un t).Alig nment = wdAlig nP aragra phCe nter '设置文字居中等rr II 标签•Tables(1).Cell(2, 1).Ra nge.l nsertAfter " nameFDSAFDSAFDSA"'文本.Tables(1).Cell(2, 2).Ra nge.l nsertAfter "MM".Ra nge(Start:=. Paragra phs(2).Ra nge.Start + 3, En d:=. Paragra phs(2) .Ra nge.Start + 8).Font.Size = 30 '选定的文本(第二段开始位置加3至8的字体)设置字体,其它的累推.Tables(1).Cell(2, 1).Ra nge.Fo nt.Size = 20 '给选定的单元格设置字体,其它的累推Set MyWordBook = Noth ing !EI ■!E it!1、对其WORD 内容设置字体样式,以及在 WORD 中插入表格,以及表格单元格融合与填充 1I ■!E it *Qp ti on Exp licitii! Private Sub Comma nd1_Click()!E_I ■!!!Dim file name As Stri ng ! ■!EjCD.ShowSave:L!1,■!Efile name = CD.file nameiiI ■!ElOutWord file nameIE,■!E■ IliMsgBox "OK"lEnd Sub ! i!EI ■!E\[ __________________!1 !E I ■!E i f End With MyWord.Visible = True !E I ■ !E i f Set MyWord = Noth ing在WORD 第一个表格的第2行第1列插入I!E I ■!!tk! Private Fu nction OutWord(ByVal file Path As Stri ng) As Booleanii,■iSet newDoc = New Word.Docume ntI With newDoc!Earagra phs(.P aragra phs.Co un t).Ra nge.F on ="宋体"!..P aragra phs (.P aragra phs.Co un t).Ra nge.F on t.Size = 10.5!E!E,■#P aragra phs(.P aragra phs.Co un t).Alig nment = wdAlig nP aragra phRightI Lj.Co nte nt.l nsertAfter " 編号:"& vbCrLf!jI.P aragra phs(.P aragra phs.Co un t).Ra nge.F on =" 宋体"!EI;I.P aragra phs(.P aragra phs.Co un t).Ra nge.F on t.Size = 26IEI.P aragra phs(.P aragra phs.Co un t).Ra nge.F on t.Bold = TrueI ■!Ei.P aragra phs(.P aragra phs.Co un t).Alig nment = wdAlig nP aragra phCe nter ii iEI ■![Co nten t.I nsertAfter vbCrLf & "XXXXXXXXX報告"& vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf !E!E!ii.P aragra phs(.P aragra phs.Co un t).Ra nge.F on ="iiiEI ■宋体"*P aragra phs (.P aragra phs.Co un t).Ra nge.F on t.Bold = Falsei■!Eifi.P aragra phs(.P aragra phs.Co un t).Alig nment = wdAlig nP aragra phLeftiEi iCo nte nt.l nsertAfter "ii项目名称:"& vbCrLf!.Co nte nt.l nsertAfter " !EI ■IE*Co nten t.I nsertAfter " 应急类型:” & vbCrLf预警状态:正常/警界/危机” & vbCrLfii!.P aragra phs(.P aragra phs.Co un t).Alig nment = wdAlig nP aragra phCe nter !E iiIf ……… … … …|HI.Tables.Add Ran ge:=.Ra nge(Start:=.Ra nge.E nd - 1, En d:=.Ra nge.E nd), NumRows:=1, NumColu mn s:=3,:■iDefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixedii[With .Tables 。
vb操作word详解Visual Basic支持一个对象集合,该集合中的对象直接对应于Microsoft Word 97中的元素,并且通过用户界面,用户熟悉这些元素中的绝大多数。
例如,Document 对象代表了一个打开的文档,Bookmark对象代表了一个文档中的书签,而Selection对象则代表了在一个文档窗口窗格中的选定容。
在Word中,每一类元素-文档、表格、段落、书签、域等等-都可以用Visual Basic的对象来表示。
要在Word中自动执行任务,可以使用这些对象的方法和属性。
关于理解和使用Microsoft Office 97对象模型的一般性容,请参阅本书的第二章“理解对象模型”。
在Microsoft Office 97中的对象模型相当丰富,其中包含了大约180个对象。
要查看Word对象模型的层次关系图,请参阅“帮助”中的“Microsoft Word 对象”。
要获得对某种特定对象的详细描述,可以在此图中单击该对象的名字,或是在“帮助”的索引中对特定对象进行搜索。
怎样显示Word Visual Basic帮助要使用Word Visual Basic帮助,必须在安装过程中选择“自定义”的安装方式,并且为Word选中“Visual Basic在线帮助”复选框。
否则,安装程序不会安装Visual Basic帮助。
如果用户已经安装好了Word,那么可以再次运行Setup程序来安装Visual Basic帮助。
要查看Word Visual Basic 帮助,可以在“Visual Basic 编辑器里的“帮助”菜单中点击“目录和索引”一项。
在“帮助主题”对话框的“目录”一表中,双击“Microsoft Word Visual Basic 参考”,然后再双击“Visual Basic 参考”。
“帮助主题”对话框会重新出现,显示出Microsoft Word Visual Basic的目录和索引。
1、对其WORD内容设置字体样式,以及在WORD中插入表格,以及表格单元格融合与填充.Option ExplicitPrivate Sub Command1_Click()Dim filename As StringCD.ShowSavefilename = CD.filenameOutWord filenameMsgBox "OK"End SubPrivate Function OutWord(ByVal filePath As String) As BooleanDim newDoc As Word.DocumentSet newDoc = New Word.DocumentWith newDoc.Paragraphs(.Paragraphs.Count) = "宋体".Paragraphs(.Paragraphs.Count).Range.Font.Size = 10.5.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphRight.Content.InsertAfter "編号:" & vbCrLf.Paragraphs(.Paragraphs.Count) = "宋体".Paragraphs(.Paragraphs.Count).Range.Font.Size = 26.Paragraphs(.Paragraphs.Count).Range.Font.Bold = True.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphCenter.Content.InsertAfter vbCrLf & "XXXXXXXXX報告" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf.Paragraphs(.Paragraphs.Count) = "宋体".Paragraphs(.Paragraphs.Count).Range.Font.Size = 15.Paragraphs(.Paragraphs.Count).Range.Font.Bold = False.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphLeft.Content.InsertAfter "项目名称:" & vbCrLf.Content.InsertAfter "应急类型:" & vbCrLf.Content.InsertAfter "预警状态:正常/警界/危机" & vbCrLf.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphCenter.Tables.Add Range:=.Range(Start:=.Range.End - 1, End:=.Range.End), NumRows:=1, NumColumns:=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixedWith .Tables(1)If .Style <> "表(格子)" Then.Style = "表(格子)"End If.ApplyStyleHeadingRows = True.ApplyStyleLastRow = True.ApplyStyleFirstColumn = True.ApplyStyleLastColumn = True.Columns.Width = 50.Rows.Height = 20End With.Paragraphs(.Paragraphs.Count) = "宋体".Paragraphs(.Paragraphs.Count).Range.Font.Size = 15.Paragraphs(.Paragraphs.Count).Range.Font.Bold = False.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphLeft.Content.InsertAfter "委托人:" & vbCrLf.Content.InsertAfter "预警机构:" & vbCrLf.Content.InsertAfter "报告负责人:" & vbCrLf.Content.InsertAfter "时间:" & vbCrLf.Paragraphs(.Paragraphs.Count).Alignment = wdAlignParagraphLeft.Tables.Add Range:=.Range(Start:=.Range.End - 1, End:=.Range.End), NumRows:=8, NumColumns:=2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixedWith .Tables(2)If .Style <> "表(格子)" Then.Style = "表(格子)"End If.ApplyStyleHeadingRows = True.ApplyStyleLastRow = True.ApplyStyleFirstColumn = True.ApplyStyleLastColumn = True.Cell(2, 1).Range.Text = "项目名称".Range.Cells(3).Row.Cells.Merge.Range.Cells(3).Range.Font.Size = 15.Range.Cells(3).Range.Text = "信息来源/文献检索范围:" & vbCrLf & vbCrLf & vbCrLf.Range.Cells(4).Row.Cells.Merge.Range.Cells(4).Range.Text = "情况描述/检索结果:" & vbCrLf & vbCrLf & vbCrLf .Range.Cells(5).Row.Cells.Merge.Range.Cells(5).Range.Text = "影响分析:" & vbCrLf & vbCrLf & vbCrLf & vbCrLf .Range.Cells(6).Row.Cells.Merge.Range.Cells(6).Range.Text = "建议:" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf.Range.Cells(7).Row.Cells.Merge.Range.Cells(7).Range.Text = "专家组成员:" & vbCrLf & vbCrLf & vbCrLf &vbCrLf & vbCrLf & vbCrLf.Range.Cells(8).Row.Cells.Merge.Range.Cells(8).Range.Text = "附件目录:" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf.Range.Cells(9).Row.Cells.Merge.Range.Cells(9).Range.Text = "报告负责人:" & vbCrLf & vbCrLf & vbCrLf & vbCrLf & " 年月日"End WithEnd WithnewDoc.SaveAs filePathnewDoc.CloseEnd Function2、VB程序操作word表格(文字、图片)很多人都知道,用vb操作excel的表格非常简单,但是偏偏项目中碰到了VB操作word表格的部分,google、baidu搜爆了,都没有找到我需要的东西。
VBA操作Word表格的常见技巧和方法Word表格是处理文档中数据的有力工具,可以用于创建、编辑和格式化各种表格。
在处理大量数据时,手动操作可能会变得繁琐和冗长。
为了提高效率,VBA(Visual Basic for Applications)可以用于自动化和简化Word表格的操作。
本文将介绍一些常见的VBA技巧和方法,以便更高效地操作Word表格。
1. 创建和插入表格在使用VBA操作Word表格之前,首先需要创建和插入表格。
表格通常是用于存储和展示数据的,可以使用VBA来动态创建表格并插入到文档中。
```vbaSub InsertTable()Dim tbl As Table'在光标位置插入一个2行3列的表格Set tbl = Selection.Tables.Add(Selection.Range, 2, 3)'设置表格样式tbl.Style = "Table Grid"'设置表格边框可见tbl.Borders.Enable = TrueEnd Sub```以上代码演示了如何在当前光标位置插入一个2行3列的表格,并设置其样式和边框。
2. 设置表格属性和样式在VBA中,我们可以设置表格的各种属性和样式,以满足特定的需求。
以下是一些常见操作的示例:```vbaSub formatTable()Dim tbl As TableSet tbl = ActiveDocument.Tables(1) '选择第一个表格'调整表格列宽tbl.Columns(1).Width = InchesToPoints(1.5)'设置表格行高tbl.Rows(1).Height = InchesToPoints(0.5)'设置表格对齐方式tbl.Rows.Alignment = wdAlignRowCentertbl.Rows.VerticalAlignment = wdCellAlignVerticalCenter'设置表格边框tbl.Borders.Enable = Truetbl.Borders.OutsideLineStyle = wdLineStyleSingletbl.Borders.InsideLineStyle = wdLineStyleSingle'设置表格颜色tbl.Shading.BackgroundPatternColor = RGB(192, 192, 192) End Sub```上述代码演示了如何设置表格的列宽、行高、对齐方式、边框样式和背景颜色。
vba操作Word Dim docPath As StringDim wordApp As New Word.ApplicationDim wordDoc As New Word.DocumentPrivate Sub CmdSelectDic_Click()Unload MeEnd SubPrivate Sub List_file(oPath As String)Dim uuFso, uuDir, uuFiles, uuObjList1.ClearSet uuFso = CreateObject("Scripting.FileSystemObject")Set uuDir = uuFso.getfolder(oPath)Set uuFiles = uuDir.FilesFor Each uuObj In uuFilesSelect Case UCase(uuFso.GetExtensionName()) Case "DOC"If Left(, 1) <> "~" ThenList1.AddItem End IfCase ElseEnd SelectNextEnd SubPrivate Sub CmdExit_Click()EndEnd SubPrivate Sub cmdShowLog_Click()Shell "notepad c:/olog.log", vbMaximizedFocusEnd SubPrivate Sub CmdStart_Click()If CHECK_TXT = 0 ThenExit SubEnd IfCmdStart.Enabled = FalseCmdExit.Enabled = FalseMe.Caption = "正在处理..."'退出所以word文档并保存wordApp.Quit TrueList2.ClearMe.ProgressBar1.Value = 0Dim docNumdocNum = 0Dim maxProcessbarmaxProcessbar = List1.ListCount'处理列表框中的每个doc文档While List1.ListCountdocNum = docNum + 1Process_wordFile docPath & "/" & List1.List(0), CInt(docNum)List2.AddItem List1.List(0)List1.RemoveItem (0)Me.ProgressBar1.Value = 100 * docNum / maxProcessbarDoEventsWendMe.Caption = "批量DOC文档处理"MsgBox "处理结束", vbInformation, "提示信息"CmdStart.Enabled = TrueCmdExit.Enabled = TrueEnd SubPrivate Sub Process_wordFile(wfilePath As String, flwID As Integer)'---------打开word文档-----------------' Set wordApp = CreateObject("Word.Application")Dim newStrDim myRange As ObjectSet wordApp = New Word.ApplicationwordApp.Visible = FalseSet wordDoc = wordApp.Documents.Open(wfilePath)Set myRange = wordDoc.Paragraphs(wordDoc.Paragraphs.Count)' '图幅编号赋值' newStr = "PTQ-" & Mid(wordDoc.Tables(1).Rows(1).Cells(1).Range.Text, 6, 2)' newStr = newStr & "-" & Left("0000", 4 - Len(CStr(flwID))) & flwID' wordDoc.Tables(1).Rows(4).Cells(2).Range.Text = newStr'' '调查表编号赋值' wordDoc.Tables(1).Rows(4).Cells(6).Range.Text = newStr & "B"''' '修改面积' newStr = wordDoc.Tables(1).Rows(6).Cells(4).Range.Text' newStr = Left(newStr, Len(newStr) - 3)'' If IsNumeric(newStr) = True Then' newStr = CDbl(newStr) / 15 '亩转换为公顷' wordDoc.Tables(1).Rows(6).Cells(4).Range.Text = newStr & "公顷"' End If'' newStr = wordDoc.Tables(1).Rows(7).Cells(4).Range.Text' newStr = Left(newStr, Len(newStr) - 3)'' If IsNumeric(newStr) = True Then' newStr = CDbl(newStr) / 15' wordDoc.Tables(1).Rows(7).Cells(4).Range.Text = newStr & "公顷"' End If'''' '修改' wordDoc.Tables(1).Rows(10).Cells(4).Range.Text = " 是√ 否 "'' '修改整个表格内字体颜色' wordDoc.Tables(1).Range.Font.Color = wdColorBlacknewStr = " 测量者:" & Trim(TxtCL.Text) & _" 校对人:" & Trim(TxtCL.Text) & " 审核人:" & Trim(TxtSh.Text)If wordDoc.Paragraphs(wordDoc.Paragraphs.Count).Range.Words.Count < 5 Then writeLog "文件:" & wfilePath & "发生错误,可能是段落末尾含有空段落!"End IfwordDoc.Paragraphs(wordDoc.Paragraphs.Count).Range.Text = newStr wordDoc.Close TruewordApp.QuitSet wordApp = NothingSet wordDoc = NothingEnd SubPrivate Sub Dir1_Change()docPath = Dir1.PathList_file (docPath)End SubPrivate Sub Drive1_Change()Dir1.Path = Drive1.DriveEnd SubPrivate Sub Form_Load()docPath = "C:/"List_file (docPath)End SubFunction RegExpNum(s As String) As StringDim p As StringDim reg As RegExpDim mc As MatchCollectionDim m As Matchp = "测量者([/s+])"Set reg = New RegExpreg.Pattern = pSet mc = reg.Execute(s)For Each m In mcp = m.ValueNext m' MsgBox "mc.Count=" & mc.CountRegExpNum = pSet mc = NothingSet reg = NothingEnd FunctionPrivate Sub TxtCL_GotFocus()'MsgBox Left(TxtCL.Text, 1)If Left(TxtCL.Text, 1) = "-" ThenTxtCL.Text = ""End IfEnd SubPrivate Sub TxtCL_LostFocus()If Trim(TxtCL.Text) = "" ThenTxtCL.Text = "-测量者-"TxtCLEnd IfEnd SubPrivate Sub txtjd_gotfocus()If Left(TxtJd.Text, 1) = "-" ThenTxtJd.Text = ""End IfEnd SubPrivate Sub txtjd_lostfocus()If Trim(TxtJd.Text) = "" ThenTxtJd.Text = "-校对人-"End IfEnd SubPrivate Sub txtSh_gotfocus()If Left(TxtSh.Text, 1) = "-" ThenTxtSh.Text = ""End IfEnd SubPrivate Sub txtSh_lostfocus()If Trim(TxtSh.Text) = "" ThenTxtSh.Text = "-审核人-"End IfEnd SubFunction CHECK_TXT()If Left(TxtSh.Text, 1) = "-" Or Left(TxtJd.Text, 1) = "-" Or Left(TxtCL.Text, 1) = "-" Then MsgBox "信息不完整!", vbInformation, "提示"CHECK_TXT = 0ElseCHECK_TXT = 1End IfEnd FunctionPrivate Sub writeLog(str As String)str = Now() & " " & strstr = str & vbCrLf & "--------------------" & vbCrOpen "c:/olog.log" For Append As #1Write #1, strClose #1End Sub。
VB操作WORD详解VB操作Word是一种常见的编程任务,可以用来自动化创建、修改和格式化Word文档。
VB是Visual Basic的简称,是一种简单易学的编程语言,广泛应用于Windows平台上的开发工作。
下面将详细介绍如何使用VB操作Word。
一、引用和初始化Word对象模型在使用VB操作Word之前,需要先引用Word对象模型。
在VB的项目中,点击“项目”菜单,选择“引用”,在弹出的对话框中找到并勾选“Microsoft Word xx.0 Object Library”(这里的xx表示Word的版本号),点击“确定”进行引用。
在VB中操作Word,首先要创建一个Word.Application对象,用来表示Word应用程序实例,在这个实例上进行后续的操作。
可以使用如下代码创建Word应用程序实例:Dim wdApp As Word.ApplicationSet wdApp = New Word.Application二、打开、创建和保存Word文档1. 打开现有的Word文档可以使用如下代码打开一个现有的Word文档:Dim wdDoc As Word.DocumentSet wdDoc = wdApp.Documents.Open("C:\path\to\your\file.docx")2. 创建新的Word文档可以使用如下代码创建一个新的Word文档:Dim wdDoc As Word.DocumentSet wdDoc = wdApp.Documents.Add3. 保存Word文档可以使用如下代码保存一个Word文档:wdDoc.SaveAs "C:\path\to\save\your\file.docx"三、操作Word文档内容1.读取和写入文本内容可以使用如下代码读取和写入文本内容:Dim strText As StringstrText = wdDoc.Range.Text '读取文档内容到字符串变量wdDoc.Range.Text = "Hello, World!" '向文档中写入文本内容2.插入和删除文本内容可以使用如下代码插入和删除文本内容:wdDoc.Range.InsertBefore "Insert Before" '在光标位置之前插入文本wdDoc.Range.InsertAfter "Insert After" '在光标位置之后插入文本wdDoc.Range.Delete '删除光标当前所在位置的文本3.格式化文本内容可以使用如下代码格式化文本内容,如设置字体、大小、颜色等: = "Arial" '设置字体为ArialwdDoc.Range.Font.Size = 12 '设置字体大小为12wdDoc.Range.Font.Color = RGB(255, 0, 0) '设置字体颜色为红色四、操作Word文档样式和格式1.设置段落样式可以使用如下代码设置段落的样式,如对齐方式、缩进等:wdDoc.Range.Paragraphs.Alignment = wdAlignParagraphCenter '设置居中对齐wdDoc.Range.Paragraphs.LeftIndent = 36 '设置左缩进为0.5英寸2.设置页面样式可以使用如下代码设置页面的样式,如边距、纸张大小等:wdDoc.PageSetup.TopMargin = 72 '设置页边距上为1英寸wdDoc.PageSetup.PaperSize = wdPaperA4 '设置纸张大小为A43.插入表格可以使用如下代码插入一个表格到Word文档:Dim wdTable As Word.TableSet wdTable = wdDoc.Tables.Add(wdDoc.Range, 3, 3) '添加3行3列的表格4.格式化表格可以使用如下代码格式化表格,如设置边框、背景颜色等:wdTable.Borders.InsideLineStyle = wdLineStyleSingle '设置内部边框为实线wdTable.Borders.OutsideLineStyle = wdLineStyleDouble '设置外部边框为双线wdTable.Rows(1).Cells(1).Shading.BackgroundPatternColor = RGB(255, 0, 0) '设置第一行第一列的背景颜色为红色五、关闭Word应用程序使用完Word应用程序后,需要关闭它以释放系统资源。
请耐心看完:问题出现得较复杂。
我的目的:将多个文档内容逐一拷贝粘贴到另一文档后面我的方法:wordapp=new word.applicationSet doc = wordapp.Documents.AddwhilepathTemp = App.Path & "\temp.doc"LoadFile rs("word"), pathTempSet doctemp = wordapp.Documents.Open(pathTemp)doctemp.Content.Selectwordapp.Selection.copySet myRange = doc.Range(Start:=doc.Content.End - 1, En d:=doc.Content.End)myRange.Select' wordapp.Selection.deletewordapp.Selection.InsertParagraphBeforewordapp.Selection.Collapse wdCollapseEndwordapp.Selection.pasteClipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"如果我的文档(待拷贝的文档,这些文档都是从数据库中读出来的,存在pathTemp文件中)都较小的话,我的程序可以顺利完成任务,如果其中一个文档较大,那么问题出现了,但是问题不是马上出现,该文档的内容能顺利从数据库下载到文件pathTemp中,也能打开到doctemp中,复制粘贴到doc中也没有问题,但是关闭doctemp时却发现隐藏的~$temp.doc并没有消失(意味着doctemp并没有关闭?),接着我把下一个文档从数据库读出放到doctemp中也能完成,temp.doc中内容正确,但是当我用Set doctemp = wordapp.Documents.Open(pathTemp)打开时却出现了问题,运行时错误‘5121’文档的名称或路径无效,请使用如下建议:....手动打开temp.doc也出现同样的错误,但是当我关掉doc(即papertemp.doc)时,打开temp.doc却是正常,而且里面数据也正常请高手指教,愿送所有分问题点数:100、回复次数:8Top1 楼faysky2(出来混,迟早是要还嘀)回复于2005-10-26 01:19:45 得分4是着释放doctemp 看看:....Clipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"Set doctemp=Nothing'--->释放掉doctempTop2 楼hapluo(言先必行,多说无益)回复于2005-10-26 20:49:54 得分0还是不行,哪位高手帮我解决,另送200分Top3 楼hapluo(言先必行,多说无益)回复于2005-10-26 20:56:53 得分0这个号所有分相送,这个号就剩500分了,数来帮我啊,分不够我另外一个号还可再加!Top4 楼hapluo(言先必行,多说无益)回复于2005-10-26 21:28:55 得分0help,Top5 楼mylord()回复于2005-10-26 21:55:46 得分2正在学习中...Top6 楼northwolves(狼行天下)回复于2005-10-26 23:46:20 得分90何必打开,直接合并不行? 试试:Private Sub Command1_Click()Dim wordapp As New Word.application, doc As New Document, pathtemp As StringSet doc = wordapp.Documents.Open(App.Path & "\papertemp.doc")doc.Content.SelectDo While Not rs.EOFpathtemp = App.Path & "\temp.doc"LoadFile rs("word"), pathtemp'你写的过程吧With wordapp.selection.InsertFile FileName:=pathtemp, ConfirmConversions:=False.InsertParagraphAfter.InsertBreak Type:=wdSectionBreakNextPage.Collapse Direction:=wdCollapseEndEnd WithKill pathtemprs.movenextLoopdoc.SaveEnd IfTop7 楼faysky2(出来混,迟早是要还嘀)回复于2005-10-26 23:48:40 得分4把doc也关掉试试:.....Clipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"doctemp.Quitdoc.QuitSet doc=Nothing Top8 楼hapluo(言先必行,多说无益)回复于2005-10-27 00:57:23 得分0northwolves(狼行天下) ,非常感谢,虽然没有问题之所在,但是绕开了问题相当于解决了问题,再次感谢!有什么办法可以把分一下相送,以示感激之情?除了多开几贴还有其他办法嘛?vb控制word的类模块,查找、替换Word文档内容在VB6.0中,操作word,使用它强大的查找、替换、删除、复制、翦切功能。
vb操作WORD大全很多人都知道,用vb操作excel的表格非常简单,但是偏偏项目中碰到了VB操作word表格的部分,google、baidu搜爆了,都没有找到我需要的东西。
到是搜索到了很多问这个问题的记录。
没办法,索性只有自己去尝试了。
下面把一些代码发上来,给需要的朋友一点提示。
打开一个已经存在的wrod文件(这个文件包含了表格)Dim WordAppDim WordSet WordApp = CreateObject("Word.Application")WordApp.Visible = TrueSet Word = WordApp.Documents.Open("c:\record.dot")知道了就很简单了,下面是选定某一个表格的一个单元格,并修改其内容Word.Tables(1).cell(1, 2)="内容"VBA中的这些数组元素下标都是从1开始的,比如excel的第一行一列也是ExSheet.Cells(1,1),而不是ExSheet.Cells(0,0),WORD的表格也是这样,不信自己试一下就知道了。
所以上面那句话的意思就是对整个word文档中的第一个表格的第一行第二列的内容改变为“内容”。
很简单吧?网上有些人在问是不是Word.Tables(1).cell(1, 2).range.text或者Word.Tables(1).cell(1, 2).text。
试一下就发现这2种都不对。
插入图片其实也很简单,代码如下:说到这,肯定又有人会问怎么在一个word里插入一个表格。
其实很简单:如果你的程序里涉及到合并及拆分单元格,那么你可能试一下这段代码:dim Tableset Table = wdApp.ActiveDocument.Tables.Add(wdApp.Application.Selection.Range, NumRows:=27, NumColumn s _:=7, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _wdAutoFitFixed)Set mySelection = wdApp.Documents.Application.SelectionmySelection.Cells.Borders(-7).LineStyle = 1'选中表格的第2行第3列table.Cell(2, 3).Select'向下移动6格,第1个参数和第3个是常数Call wdBook.Application.Selection.MoveDown(5, 6, 1)'合并wdBook.Application.Selection.Cells.Merge'拆分成7行2列Call wdBook.Application.Selection.Cells.Split(7, 2, True)如果大家碰到了更复杂的程序,用程序生成起来比较麻烦,那么你就可以用模板来实现了?你可以先用word做一个模板,把表格什么的全都先写好,然后保存成模板文件。
请耐心看完:问题出现得较复杂。
我的目的:将多个文档内容逐一拷贝粘贴到另一文档后面我的方法:wordapp=new word.applicationSet doc = wordapp.Documents.AddwhilepathTemp = App.Path & "\temp.doc"LoadFile rs("word"), pathTempSet doctemp = wordapp.Documents.Open(pathTemp)doctemp.Content.Selectwordapp.Selection.copySet myRange = doc.Range(Start:=doc.Content.End - 1, En d:=doc.Content.End)myRange.Select' wordapp.Selection.deletewordapp.Selection.InsertParagraphBeforewordapp.Selection.Collapse wdCollapseEndwordapp.Selection.pasteClipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"如果我的文档(待拷贝的文档,这些文档都是从数据库中读出来的,存在pathTemp文件中)都较小的话,我的程序可以顺利完成任务,如果其中一个文档较大,那么问题出现了,但是问题不是马上出现,该文档的内容能顺利从数据库下载到文件pathTemp中,也能打开到doctemp中,复制粘贴到doc中也没有问题,但是关闭doctemp时却发现隐藏的~$temp.doc并没有消失(意味着doctemp并没有关闭?),接着我把下一个文档从数据库读出放到doctemp中也能完成,temp.doc中内容正确,但是当我用Set doctemp = wordapp.Documents.Open(pathTemp)打开时却出现了问题,运行时错误‘5121’文档的名称或路径无效,请使用如下建议:....手动打开temp.doc也出现同样的错误,但是当我关掉doc(即papertemp.doc)时,打开temp.doc却是正常,而且里面数据也正常请高手指教,愿送所有分问题点数:100、回复次数:8Top1 楼faysky2(出来混,迟早是要还嘀)回复于2005-10-26 01:19:45 得分4是着释放doctemp 看看:....Clipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"Set doctemp=Nothing'--->释放掉doctempTop2 楼hapluo(言先必行,多说无益)回复于2005-10-26 20:49:54 得分0还是不行,哪位高手帮我解决,另送200分Top3 楼hapluo(言先必行,多说无益)回复于2005-10-26 20:56:53 得分0这个号所有分相送,这个号就剩500分了,数来帮我啊,分不够我另外一个号还可再加!Top4 楼hapluo(言先必行,多说无益)回复于2005-10-26 21:28:55 得分0help,Top5 楼mylord()回复于2005-10-26 21:55:46 得分2正在学习中...Top6 楼northwolves(狼行天下)回复于2005-10-26 23:46:20 得分90何必打开,直接合并不行? 试试:Private Sub Command1_Click()Dim wordapp As New Word.application, doc As New Document, pathtemp As StringSet doc = wordapp.Documents.Open(App.Path & "\papertemp.doc")doc.Content.SelectDo While Not rs.EOFpathtemp = App.Path & "\temp.doc"LoadFile rs("word"), pathtemp'你写的过程吧With wordapp.selection.InsertFile FileName:=pathtemp, ConfirmConversions:=False.InsertParagraphAfter.InsertBreak Type:=wdSectionBreakNextPage.Collapse Direction:=wdCollapseEndEnd WithKill pathtemprs.movenextLoopdoc.SaveEnd IfTop7 楼faysky2(出来混,迟早是要还嘀)回复于2005-10-26 23:48:40 得分4把doc也关掉试试:.....Clipboard.Cleardoctemp.Close wdDoNotSaveChangesdoc.SaveAs App.Path & "\papertemp.doc"doctemp.Quitdoc.QuitSet doc=Nothing Top8 楼hapluo(言先必行,多说无益)回复于2005-10-27 00:57:23 得分0northwolves(狼行天下) ,非常感谢,虽然没有问题之所在,但是绕开了问题相当于解决了问题,再次感谢!有什么办法可以把分一下相送,以示感激之情?除了多开几贴还有其他办法嘛?vb控制word的类模块,查找、替换Word文档内容在VB6.0中,操作word,使用它强大的查找、替换、删除、复制、翦切功能。
还可以把特定字符替换成图片。
有了它你就可以使用数据库中的内容或图片文件替换word文件中的特定字符。
只要把下列内容复制到写字板中,另存为SetWord.cls文件,然后在把它添加到工程中,就可以使用了。
VERSION 1.0 CLASSBEGINMultiUse = -1 'TruePersistable = 0 'NotPersistableDataBindingBehavior = 0 'vbNoneDataSourceBehavior = 0 'vbNoneMTSTransactionMode = 0 'NotAnMTSObjectENDAttribute VB_Name = "SetWord"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = TrueAttribute VB_PredeclaredId = FalseAttribute VB_Exposed = FalsePrivate mywdapp As Word.ApplicationPrivate mysel As Object'属性值的模块变量Private C_TemplateDoc As StringPrivate C_newDoc As StringPrivate C_PicFile As StringPrivate C_ErrMsg As IntegerPublic Event HaveError()Attribute HaveError.VB_Description = "出错时激发此事件.出错代码为ErrMsg属性"'***************************************************************'ErrMsg代码:1-word没有安装2-缺少参数3-没权限写文件' 4-文件不存在''***************************************************************Public Function ReplacePic(FindStr As String, Optional Time As Integer = 0) As Integer Attribute ReplacePic.VB_Description = "查找FindStr,并替换为PicFile所指向的图片文件,替换次数由time参数确定,为0时,替换所有"'********************************************************************************'从Word.Range对象mysel中查找所有FindStr,并替换为PicFile图像' 替换次数由time参数确定,为0时,替换所有'******************************************************************************** If Len(C_PicFile) = 0 ThenC_ErrMsg = 2Exit FunctionEnd IfDim i As IntegerDim findtxt As Booleanmysel.Find.ClearFormattingmysel.Find.Replacement.ClearFormattingWith mysel.Find.Text = FindStr.Replacement.Text = "".Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = FalseEnd Withmysel.HomeKey Unit:=wdStoryfindtxt = mysel.Find.Execute(Replace:=True)If Not findtxt ThenReplacePic = 0Exit FunctionEnd Ifi = 1Do While findtxtmysel.InlineShapes.AddPicture FileName:=C_PicFileIf i = Time Then Exit Doi = i + 1mysel.HomeKey Unit:=wdStoryfindtxt = mysel.Find.Execute(Replace:=True)LoopReplacePic = iEnd FunctionPublic Function FindThis(FindStr As String) As BooleanAttribute FindThis.VB_Description = "查找FindStr,如果模板中有FindStr则返回True" If Len(FindStr) = 0 ThenC_ErrMsg = 2Exit FunctionEnd Ifmysel.Find.ClearFormattingmysel.Find.Replacement.ClearFormattingWith mysel.Find.Text = FindStr.Replacement.Text = "".Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = FalseEnd Withmysel.HomeKey Unit:=wdStoryFindThis = mysel.Find.ExecuteEnd FunctionPublic Function ReplaceChar(FindStr As String, RepStr As String, Optional Time As Integer = 0) As IntegerAttribute ReplaceChar.VB_Description = "查找FindStr,并替换为RepStr,替换次数由time 参数确定,为0时,替换所有"'********************************************************************************'从Word.Range对象mysel中查找FindStr,并替换为RepStr' 替换次数由time参数确定,为0时,替换所有'********************************************************************************Dim findtxt As BooleanIf Len(FindStr) = 0 ThenC_ErrMsg = 2RaiseEvent HaveErrorExit FunctionEnd Ifmysel.Find.ClearFormattingmysel.Find.Replacement.ClearFormattingWith mysel.Find.Text = FindStr.Replacement.Text = RepStr.Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = FalseEnd WithIf Time > 0 ThenFor i = 1 To Timemysel.HomeKey Unit:=wdStoryfindtxt = mysel.Find.Execute(Replace:=wdReplaceOne) If Not findtxt Then Exit ForNextIf i = 1 And Not findtxt ThenReplaceChar = 0ElseReplaceChar = iEnd IfElsemysel.Find.Execute Replace:=wdReplaceAllEnd IfEnd FunctionPublic Function GetPic(PicData() As Byte, FileName As String) As Boolean Attribute GetPic.VB_Description = "把图像数据PicData,存为PicFile指定的文件" '********************************************************************************'把图像数据PicData,存为PicFile指定的文件'********************************************************************************On Error Resume NextIf Len(FileName) = 0 ThenC_ErrMsg = 2RaiseEvent HaveErrorExit FunctionEnd IfOpen FileName For Binary As #1If Err.Number <> 0 ThenC_ErrMsg = 3Exit FunctionEnd If'二进制文件用Get,Put存放,读取数据Put #1, , PicDataClose #1C_PicFile = FileNameGetPic = TrueEnd FunctionPublic Sub DeleteToEnd()Attribute DeleteToEnd.VB_Description = "删除从当前位置到结尾的所有内容" mysel.EndKey Unit:=wdStory, Extend:=wdExtendmysel.Delete Unit:=wdCharacter, Count:=1End SubPublic Sub MoveEnd()Attribute MoveEnd.VB_Description = "光标移动到文档结尾"'光标移动到文档结尾mysel.EndKey Unit:=wdStoryEnd SubPublic Sub GotoLine(LineTime As Integer)mysel.GoTo What:=wdGoToLine, Which:=wdGoToFirst, Count:=LineTime, Name:="" End SubPublic Sub OpenDoc(view As Boolean)Attribute OpenDoc.VB_Description = "打开Word文件,View确定是否显示Word界面" On Error Resume Next'********************************************************************************'打开Word文件,并给全局变量mysel赋值'********************************************************************************If Len(C_TemplateDoc) = 0 Thenmywdapp.Documents.AddElsemywdapp.Documents.Open (C_TemplateDoc)End IfIf Err.Number <> 0 ThenC_ErrMsg = 4RaiseEvent HaveErrorExit SubEnd Ifmywdapp.Visible = viewmywdapp.ActivateSet mysel = mywdapp.Application.Selection'mysel.SelectEnd SubPublic Sub OpenWord()On Error Resume Next'******************************************************************************** '打开Word程序,并给全局变量mywdapp赋值'******************************************************************************** Set mywdapp = CreateObject("word.application")If Err.Number <> 0 ThenC_ErrMsg = 1RaiseEvent HaveErrorExit SubEnd IfEnd SubPublic Sub ViewDoc()Attribute ViewDoc.VB_Description = "显示Word程序界面" mywdapp.Visible = TrueEnd SubPublic Sub AddNewPage()Attribute AddNewPage.VB_Description = "插入分页符"mysel.InsertBreak Type:=wdPageBreakEnd SubPublic Sub WordCut()Attribute WordCut.VB_Description = "剪切模板所有内容到剪切板"'保存模板页面内容mysel.WholeStorymysel.Cutmysel.HomeKey Unit:=wdStoryEnd SubPublic Sub WordCopy()Attribute WordCopy.VB_Description = "拷贝模板所有内容到剪切板"mysel.WholeStorymysel.Copymysel.HomeKey Unit:=wdStoryEnd SubPublic Sub WordDel()mysel.WholeStorymysel.Deletemysel.HomeKey Unit:=wdStoryEnd SubPublic Sub WordPaste()Attribute WordPaste.VB_Description = "拷贝剪切板内容到当前位置"'插入模块内容mysel.PasteEnd SubPublic Sub CloseDoc()Attribute CloseDoc.VB_Description = "关闭Word文件模板"'******************************************************************************** '关闭Word文件模本'******************************************************************************** On Error Resume Nextmywdapp.ActiveDocument.Close FalseIf Err.Number <> 0 ThenC_ErrMsg = 3Exit SubEnd IfEnd SubPublic Sub QuitWord()'******************************************************************************** '关闭Word程序'******************************************************************************** On Error Resume Nextmywdapp.QuitIf Err.Number <> 0 ThenC_ErrMsg = 3Exit SubEnd IfEnd SubPublic Sub SavetoDoc()Attribute SavetoDoc.VB_Description = "保存当前文档为FileName指定文件" On Error Resume Next'并另存为文件FileNameIf Len(C_newDoc) = 0 ThenC_ErrMsg = 2RaiseEvent HaveErrorExit SubEnd Ifmywdapp.ActiveDocument.SaveAs (C_newDoc)If Err.Number <> 0 ThenC_ErrMsg = 3RaiseEvent HaveErrorExit SubEnd IfEnd SubPublic Property Get TemplateDoc() As StringAttribute TemplateDoc.VB_Description = "模板文件名."TemplateDoc = C_TemplateDocEnd PropertyPublic Property Let TemplateDoc(ByVal vNewValue As String)C_TemplateDoc = vNewValueEnd PropertyPublic Property Get newdoc() As StringAttribute newdoc.VB_Description = "执行CloseDoc方法时,将模板文件另存为此文件名指定的新文件.如果不指定,在执行CloseDoc方法时,将产生一个错误"newdoc = C_newDocEnd PropertyPublic Property Let newdoc(ByVal vNewValue As String)C_newDoc = vNewValueEnd PropertyPublic Property Get PicFile() As StringAttribute PicFile.VB_Description = "图像文件名"PicFile = C_PicFileEnd PropertyPublic Property Let PicFile(ByVal vNewValue As String)C_PicFile = vNewValueEnd PropertyPublic Property Get ErrMsg() As IntegerAttribute ErrMsg.VB_Description = "错误信息.ErrMsg代码: 1-word没有安装2-缺少参数3-没权限写文件4-文件不存在"ErrMsg = C_ErrMsgEnd Property请问如何正确杀掉word进程?楼主btl19792008(btl19792008)2005-11-04 17:05:03 在VB / 数据库(包含打印,安装,报表) 提问我的word程序运行几次,在资源管理器中就会出现很多word进程。