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做一个模板,把表格什么的全都先写好,然后保存成模板文件。
VBA在Word中的应用技巧总结随着科技的不断发展,计算机程序在日常工作中的重要性也越来越显著。
Visual Basic for Applications(VBA)是一种支持自动化控制的编程语言,它在Microsoft Office套件中被广泛使用。
作为常用的文字处理软件,Word中的VBA功能强大且灵活,能够帮助用户更高效地处理文档。
在本文中,将总结VBA在Word中的应用技巧,帮助读者更好地利用这一功能。
一、录制宏:VBA的入门技巧首先,录制宏是学习VBA的入门技巧之一。
在Word中,可以通过录制宏来记录一系列的操作步骤,然后利用录制的宏来自动执行这些操作。
录制宏简化了繁琐的手动操作,提高了工作效率。
录制宏的具体步骤是:点击“开发工具”选项卡中的“宏”按钮,选择“录制新宏”。
此时,Word会记录下用户的所有操作,例如选择文字格式、插入图片、调整页面布局等。
在录制过程中,可以随时点击“暂停录制”按钮暂停录制操作,点击“停止录制”按钮结束录制。
利用录制的宏,可以轻松实现重复性的任务,节省大量时间。
二、自定义宏:根据需求编写VBA代码除了录制宏,用户还可以根据需求编写自定义的VBA代码。
通过自定义宏,无需手动操作,可以实现更加复杂的任务。
编写自定义宏的步骤是:1. 打开VBA编辑器,点击“开发工具”选项卡中的“宏”按钮,选择“宏编辑器”选项。
2. 在VBA编辑器中,可以编写各种VBA代码。
例如,使用VBA代码控制文本的格式,调整页面的边距,插入表格,或者自动生成索引等。
需要说明的是,编写VBA代码需要一定的编程基础。
对于初学者来说,可以通过阅读VBA相关的教程或者参考VBA的官方文档来学习。
通过自定义宏,用户可以根据自己的需求,深入利用VBA的功能,实现更加个性化的任务。
三、循环和判断:优化重复性任务在处理大量文档或者重复性任务时,循环和判断结构是非常实用的VBA技巧。
循环结构可以通过编写循环代码块来反复执行某一段代码,直到满足特定条件才停止。
VBA中的操作Word文档的技巧在VBA中操作Word文档是自动化办公的重要一环,通过使用VBA编程语言,我们可以实现对Word文档的自动创建、编辑和格式化等操作。
本文将介绍一些常用的VBA技巧,帮助您更好地操作Word文档。
1. 打开Word文档:在VBA中,使用`Documents.Open`方法可以打开一个Word文档。
您可以指定文档的路径和名称,还可以设置一些可选参数,例如是否以只读模式打开。
2. 创建新的Word文档:通过`Documents.Add`方法可以创建一个新的Word文档。
您可以选择在创建文档时是否要基于现有的模板进行创建,并可以指定模板的路径和名称。
3. 保存Word文档:使用`Document.Save`方法可以保存当前的Word文档,您可以指定路径和名称,还可以选择是否另存为其他格式。
4. 关闭Word文档:通过`Document.Close`方法可以关闭当前的Word文档,同时保存对文档的修改。
您可以使用可选参数来控制是否强制保存。
5. 插入文本:使用`Selection.TypeText`方法可以在当前光标位置插入文本。
您可以通过VBA代码来控制插入的文本内容和格式。
6. 插入图片:通过`InlineShapes.AddPicture`方法可以在当前位置插入图片。
您可以指定图片的路径和名称,并可以设置插入图片的位置和大小。
7. 设置字体样式:可以使用`Selection.Font`属性来设置文本的字体样式,例如字体名称、字号、加粗、斜体等。
8. 设置段落格式:通过`Selection.ParagraphFormat`属性可以设置段落的格式,例如对齐方式、缩进、行间距等。
9. 遍历文档内容:可以通过VBA的循环结构来遍历文档的每个段落、句子、单词或字符,并可以对其进行相应的操作。
10. 替换文本:使用`Selection.Find`和`Selection.Replace`方法可以查找和替换文本。
[追加500分求教] VB操作WORD问题悬赏分:200 - 解决时间:2007-7-28 11:42说明,用VB操作WORD,以下源码第一次操作完全正常,正常打开,正常替换,正常退出。
进程中并没有留下windword的进程,但第二次继续操作时就出问题,运行到ReplaceWord()就出现462错误,关闭程序重新开始又正常。
请指教出错及解决原因,追加到500分'=============打开word==============Function OpenWord(FileName) '打开指定word文档Dim wordApp As New Word.ApplicationDim wordDoc As New Word.DocumentSet wordApp = CreateObject("Word.Application")wordApp.Visible = FalseSet wordDoc = wordApp.Documents.Open(FileName)End Function============替换关键字===========Function ReplaceWord(SearchStr, ReplaceStr) '全部替换函数Selection.Find.ClearFormattingSelection.Find.Replacement.ClearFormattingWith Selection.Find.Text = SearchStr.Replacement.Text = ReplaceStr.Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = FalseEnd WithSelection.Find.Execute Replace:=wdReplaceAllEnd Function'==================另存为===================Function SaveAsWord(DiskStr, NameStr)ChangeFileOpenDirectory DiskStrActiveDocument.SaveAs FileName:=NameStr, FileFormat:=wdFormatDocument _ , LockComments:=False, Password:="", AddToRecentFiles:=True, _ WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _ SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _ FalseApplication.Documents.CloseApplication.QuitEnd Function'===================清除对象============Function CloseWord()Set wordDoc = Nothing '清除文件实例Set wordApp = Nothing '清除WORD实例End Function问题补充:根据《小fisher》的答案,已经解决问题,另外在SaveAsWord过程中,ChangeFileOPenDirectory DiskStr更改为ChangeFileOpenDirectory DiskStr ,ActiveDocument.SaveAs更改为wordDoc.SaveAs,再加上原先《小fisher》提到要更改的地方,已经完美解决,谢谢!!PS:由于百度只能2次提高悬赏,每次50分,所以现在只有200分,未能对现500分的诺言,所以只有另开贴来加送300分!提问者:有野问 - 经理五级最佳答案1) Function ReplaceWord(SearchStr, ReplaceStr) '全部替换函数Selection.Find.ClearFormattingSelection.Find.Replacement.ClearFormattingWith Selection.Find.......这个函数过程有错误!因为Selection是word的对象而不是VB的对象,所以不能在VB中直接引用,必须用wordApp.Selection替换掉Selection才行!这段代码在word VBA中调试不会出问题,但移植到VB中时要注意。
1. ActiveWindow.Panes(2).Close2.End If3.If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then4. = wdPrintView5.End If6. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader7. Selection.TypeText Text:="办公室常用工具"8. = wdSeekMainDocument9.10.'隐藏页眉的横线11. WordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Borders(wdBorderBottom).Visible = False12.13.'取得页眉的内容14. Debug.Print WordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Text '获取WORD第一节的页眉的文字内容15.16.17.'设置页脚18.If <> wdPaneNone Then19. ActiveWindow.Panes(2).Close20.End If21.If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then22. = wdPrintView23.End If24. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader25.If = True Then26. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter27.Else28. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader29.End If30. Selection.TypeText Text:="2021年"'设置页脚31. Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldNumPages32. = wdSeekMainDocument33.34. ActiveDocument.SaveAs "c:\MyWord.doc"'保存最后生成的word文档35.36.Errhandler:37.Exit Sub38.End Sub39.40.Private Sub Form_Unload(Cancel As Integer)41.On Error Resume Next42. WordApp.Quit43.Set WordApp = Nothing44.End Sub效果图如下:2、控制Word文档中的文本框对象[vb] view plaincopy1.'先引用Microsoft Word 11.0 Object Library2.Option Explicit3.4.Dim WordApp As Word.Application '创立Word应用程序5.6.Private Sub Command1_Click()7.On Error GoTo Errhandler8. CommonDialog1.Filter = "MS Office Word(*.Doc)|*.Doc|AllFile(*.*)|*.*"9. CommonDialog1.FilterIndex = 110. CommonDialog1.ShowOpen11.Set WordApp = New Word.Application '实例化12. CommonDialog1.FileName '翻开Word13.If Documents.Count >= 1 Then14. Text1.Text = "翻开的Word" & & vbCrLf & vbCrLf15.End If16. WordApp.Visible = True'显示 Office Word 界面17.'或者Application.Visible = True18. WordApp.DisplayAlerts = False'不提示保存对话框19.20. unit:=wdStory '将光标移到文档末尾21. = 122. = "黑体"23. = 1824. Text:="在Word"25. WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter '居中显示26.27.'创立文本框对象,座标〔100,100〕,宽度200,高度20028.With ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 400, 300).Fill29.'.Transparency = 1 '设置透明色30. .ForeColor = vbRed '设置前景颜色31. .UserPicture ("F:\资料\My Pictures\758254_960x1000_0.jpg") '设置文本框对象的背景图片32.End With33. ActiveDocument.Shapes(1). = "这是一个美女"'给文本框赋值34.'ActiveDocument.Shapes(1).Line.Transparency = 1 '设置透明边框线条35.36.'再创立一个透明背景的文本框对象37.With ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 400, 400, 300).Fill38. .Transparency = 1 '设置透明色背景39. .ForeColor = vbRed '设置前景颜色40.End With41. ActiveDocument.Shapes(2). = "这是一个透明背景的文本框"'给文本框赋值42.'ActiveDocument.Shapes(2).Line.Transparency = 1 '设置透明边框线条43.44.'下面是获取文本框对象的内容45.Dim i As Long46.For i = 1 To47. Text1.Text = Text1.Text & ("第" & i & "个文本框的内容:" & ActiveDocument.Shapes(i).TextFrame.TextRange.Text & vbCrLf)48.Next49.50. ActiveDocument.SaveAs "c:\MyWord.doc"'保存最后生成的word文档51.52.Errhandler:53.Exit Sub54.End Sub55.56.Private Sub Form_Unload(Cancel As Integer)57.On Error Resume Next58. WordApp.Quit59.Set WordApp = Nothing60.End Sub效果图如下:3、在Word文档中设置Excel风格的页码[vb] view plaincopy1.'先引用Microsoft Word 11.0 Object Library2.Option Explicit3.4.Dim WordApp As Word.Application '创立Word应用程序5.Dim WordDoc As Word.Document '创立Word文档对象6.7.Private Sub Command1_Click()8.Dim i As Long9.On Error GoTo Errhandler10. CommonDialog1.Filter = "Word(*.Doc)|*.Doc|AllFile(*.*)|*.*"11. CommonDialog1.FilterIndex = 112. CommonDialog1.ShowOpen13.Set WordApp = New Word.Application '实例化14.Set WordDoc = WordApp.Documents.Open(CommonDialog1.FileName) '选择并翻开Word15. WordApp.Visible = True'显示 Office Word 界面16.'或者Application.Visible = True17. WordApp.DisplayAlerts = False'不提示保存对话框18.19.'设置Word文档第一页页码20.Dim WordRange As Range21.Set WordRange = WordApp.ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range22.23.With WordRange24. .InsertAfter "第"25. .Font.Size = 1426. .Collapse Direction:=wdCollapseEnd27.28.'插入页码域29. .Fields.Add Range:=WordRange, Type:=wdFieldEmpty, Text:="PAGE \* Arabic ", PreserveFormatting:=True30. .Expand unit:=wdWord31. .InsertAfter "页 "32.33. .InsertAfter "共"34. .Collapse Direction:=wdCollapseEnd35.36.'插入页数域37. .Fields.Add Range:=WordRange, Type:=wdFieldEmpty, Text:="NUMPAGES \* Arabic ", PreserveFormatting:=True38. .Expand unit:=wdWord39. .InsertAfter "页"40.41. .InsertAfter "【我的Word ChenJL1031〔东方之珠〕】"42. .ParagraphFormat.Alignment = wdAlignParagraphRight '右对齐43.End With44.45.'Text1.Text = WordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Text46.47.Set WordRange = Nothing48. ActiveDocument.SaveAs "c:\MyWord.doc"'保存最后生成的word文档49.50.Errhandler:51.Exit Sub52.End Sub53.54.Private Sub Form_Unload(Cancel As Integer)55.On Error Resume Next56. WordApp.Quit57.Set WordApp = Nothing58.End Sub效果图如下:。
VBA操作Word表格的技巧与应用Word是一个功能强大的文字处理软件,广泛应用于办公和学习中。
其中的表格功能可以帮助我们整理数据和展示信息,提高工作效率。
借助Visual Basic for Applications(VBA),我们可以更加灵活和高效地操作Word表格。
本文将介绍一些VBA操作Word表格的技巧和应用,帮助读者深入了解并运用这些功能。
1. 创建和插入表格要使用VBA操作Word表格,首先我们需要了解如何创建和插入表格。
可以使用`Documents.Add`方法来创建一个新的文档,并在其中插入一个表格。
例如,下面的代码将创建一个包含4行3列的表格:```VBASub CreateAndInsertTable()Dim tbl As TableSet tbl = Documents.Add.Tables.Add(Selection.Range, 4, 3) End Sub```使用`Add`方法可以创建一个新的表格,指定表格的插入位置以及表格的行数和列数。
`Selection.Range`参数表示表格将插入到光标所在的位置。
2. 设置表格样式和格式VBA还可以帮助我们设置表格的样式和格式,使其更加美观和易读。
通过设置表格的属性,我们可以调整表格的边框、字体、颜色等。
例如,下面的代码将设置表格的边框为实线,边框的颜色为红色:```VBASub SetTableStyle()Dim tbl As TableSet tbl = Selection.Tables(1)tbl.Borders.InsideLineStyle = wdLineStyleSingletbl.Borders.InsideColor = wdColorRedtbl.Borders.OutsideLineStyle = wdLineStyleSingletbl.Borders.OutsideColor = wdColorRedEnd Sub```通过访问`Borders`对象并设置其属性,我们可以轻松地调整表格的边框样式和颜色。
Word中VBA编程学习总结:Word编辑过程,存在大量重复操作,借助VBA程序,简化操作,实现一键word文档格式化。
但Word VBA中,Word对象、方法、属性过多,给编程带来不小的难题。
另外word本身格式术语极其之多,很多文档格式非常混乱,相对excel VBA来说难度比较大。
为此,在word编辑过程中,总结出哪些重复操作,针对性的编辑一些通用程序,例如:全选表格,全选图片,文件夹内所有文件内容替换,不同节中设置页眉页脚,为所有图表添加题注等;但还有一部分操作,因需求不确定,程序化难度较大,例如:如何一键设置列表级别,非内嵌图片的处理等。
第一部分文件夹中文件处理1.当前word文件位置,所有word文件转化为pdf1.1关键的一些语句DIR 指令,遍历文件夹内所有word文档,配合Do while…Loop,即可操作所有文件。
ExportAsFixedFormat 指令,转化为某一格式,设置exportformat:=wdExportFormatPDF 即为pdf格式。
1.2程序举例:Sub DocToPdf()'Dim myPath, myName, myName1 As StringDim SaveAsPDF As StringDim arr() As StringDim wdDoc As DocumentApplication.ScreenUpdating = FalsemyPath = ActiveDocument.Path & "\"myName = Dir(myPath & "*.doc*") '遍历文件夹内所有word文档myName1 = Do While myName <> ""Set wdDoc = Application.Documents.Open(myPath & myName, ReadOnly = True)'取得每个word文档对象,以下命令可根据实际情况调整,此处为另存pdfarr = Split(myName, ".")SaveAsPDF = myPath & arr(0) & ".pdf"wdDoc.ExportAsFixedFormat outputfilename:=SaveAsPDF, exportformat:=wdExportFormatPDFIf myName <> myName1 Then wdDoc.ClosemyName = DirSet wdDoc = NothingLoopApplication.ScreenUpdating = TrueEnd Sub第二部分图表处理1.选中所有表格1.1关键的一些语句For each t In Activedocument.Tables … Next 该语句可以遍历当前文档内所有表格,tables 代表文档中的表格集合。
VB操作word总结第一篇:VB操作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 缺少参数3文件不存在' '*************************************************************** 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 Then C_ErrMsg = 2 Exit Function End If Dim i As Integer Dim findtxt As Boolean mysel.Find.ClearFormattingmysel.Find.Replacement.ClearFormatting With mysel.Find.Text = FindStr.Replacement.Text = “".Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = False End With mysel.HomeKey Unit:=wdStory findtxt = mysel.Find.Execute(Replace:=True)If Not findtxt Then ReplacePic = 0 Exit Function End If i = 1 Do While findtxt mysel.InlineShapes.AddPicture FileName:=C_PicFile If i = Time Then Exit Do i = i + 1 mysel.HomeKey Unit:=wdStory findtxt = mysel.Find.Execute(Replace:=True)Loop ReplacePic = i End Function Public Function FindThis(FindStr As String)As Boolean Attribute FindThis.VB_Description = ”查找FindStr,如果模板中有FindStr则返回True“ If Len(FindStr)= 0 Then C_ErrMsg = 2 Exit Function End If mysel.Find.ClearFormatting mysel.Find.Replacement.ClearFormatting With mysel.Find.Text = FindStr.Replacement.Text = ”“.Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = False End With mysel.HomeKey Unit:=wdStory FindThis = mysel.Find.Execute End Function Public Function ReplaceChar(FindStr As String, RepStr As String, Optional Time As Integer = 0)As Integer Attribute ReplaceChar.VB_Description = ”查找FindStr,并替换为RepStr,替换次数由time参数确定,为0时,替换所有“ '**************************************************************** **************** '从Word.Range对象mysel中查找FindStr,并替换为RepStr ' 替换次数由time参数确定,为0时,替换所有'************************************************************** ****************** Dim findtxt As Boolean If Len(FindStr)= 0 Then C_ErrMsg = 2 RaiseEvent HaveError Exit Function End If mysel.Find.ClearFormattingmysel.Find.Replacement.ClearFormatting With mysel.Find.Text = FindStr.Replacement.Text = RepStr.Forward = True.Wrap = wdFindContinue.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = False End WithIf Time > 0 Then For i = 1 To Time mysel.HomeKey Unit:=wdStory findtxt = mysel.Find.Execute(Replace:=wdReplaceOne)If Not findtxt Then Exit For Next If i = 1 And Not findtxt Then ReplaceChar = 0 Else ReplaceChar = i End If Else mysel.Find.Execute Replace:=wdReplaceAll End If End FunctionPublic Function GetPic(PicData()As Byte, FileName As String)As Boolean Attribute GetPic.VB_Description = ”把图像数据PicData,存为PicFile指定的文件“ '**************************************************************** **************** '把图像数据PicData,存为PicFile指定的文件'************************************************************** ****************** On Error Resume Next If Len(FileName)= 0 Then C_ErrMsg = 2 RaiseEvent HaveError Exit Function End If Open FileName For Binary As #1 If Err.Number <> 0 Then C_ErrMsg = 3 Exit Function End If '二进制文件用Get,Put存放,读取数据 Put #1, , PicData Close #1 C_PicFile = FileName GetPic = True End FunctionPublic Sub DeleteToEnd()AttributeDeleteToEnd.VB_Description = ”删除从当前位置到结尾的所有内容“ mysel.EndKey Unit:=wdStory, Extend:=wdExtend mysel.Delete Unit:=wdCharacter, Count:=1 End Sub Public Sub MoveEnd()Att ribute MoveEnd.VB_Description = ”光标移动到文档结尾“ '光标移动到文档结尾mysel.EndKey Unit:=wdStory End Sub Public Sub GotoLine(LineTime As Integer)mysel.GoTo What:=wdGoT oLine, Which:=wdGoToFirst, Count:=LineTime, Name:=”“ End Sub Public Sub OpenDoc(view As Boolean)Attribut e OpenDoc.VB_Description = ”打开Word文件,View确定是否显示Word界面“ On Error Resume Next '******************************************************************* ************* '打开Word文件,并给全局变量mysel赋值'************************************************************** ****************** If Len(C_TemplateDoc)= 0 Then mywdapp.Documents.Add Else mywdapp.Documents.Open(C_TemplateDoc)End If If Err.Number <> 0 Then C_ErrMsg = 4 RaiseEvent HaveError Exit Sub End If mywdapp.Visible = view mywdapp.Activate Set mysel = mywdapp.Application.Selection 'mysel.SelectEnd Sub Public Sub OpenWord()On Error Resume Next '******************************************************************* ************* '打开Word程序,并给全局变量mywdapp赋值'************************************************************** ****************** Set mywdapp = CreateObject(”word.application“)If Err.Number <> 0 Then C_ErrMsg = 1 RaiseEvent HaveError Exit Sub End If End Sub Public Sub ViewDoc()Attribute ViewDoc.VB_Description = ”显示Word 程序界面“ mywdapp.Visible = True End Sub Public SubAddNewPag e()Attribute AddNewPage.VB_Description = ”插入分页符“ mysel.InsertBreak Type:=wdPageBreak End Sub Public Sub WordCut()Attribute WordCut.VB_Description = ”剪切模板所有内容到剪切板“ '保存模板页面内容 mysel.WholeStory mysel.Cut mysel.HomeKey Unit:=wdStory End Sub Public Sub WordCopy()Attribute WordCopy.VB_Description = ”拷贝模板所有内容到剪切板“ mysel.WholeStory mysel.Copy mysel.HomeKey Unit:=wdStory End Sub Public Sub WordDel()mysel.WholeStory mysel.Delete mysel.HomeKey Unit:=wdStory End Sub Public Sub WordPaste()Attribute WordPaste.VB_Descripti on = ”拷贝剪切板内容到当前位置“ '插入模块内容mysel.Paste End Sub Public Sub CloseDoc()Attribute CloseDoc.VB_Description = ”关闭Word文件模板“ '**************************************************************** **************** '关闭Word文件模本'******************************************************************* ************* On Error Resume Nextmywdapp.ActiveDocument.Close False If Err.Number <> 0 Then C_ErrMsg = 3 Exit Sub End If End Sub Public Sub QuitWord()'******************************************************* ************************* '关闭Word程序'************************************************************** ****************** On Error Resume Next mywdapp.Quit If Err.Number <> 0 Then C_ErrMsg = 3 Exit Sub End If End Sub Public Sub SavetoDoc()Attribute SavetoDoc.VB_Description = ”保存当前文档为FileName指定文件“ On Error Resume Next '并另存为文件FileName If Len(C_newDoc)= 0 Then C_ErrMsg = 2 RaiseEvent HaveError Exit Sub End Ifmywdapp.ActiveDocument.SaveAs(C_newDoc)If Err.Number <> 0 Then C_ErrMsg = 3 RaiseEvent HaveError Exit Sub End If End SubPublic Property Get TemplateDoc()As String Attribute TemplateDoc.VB_Description = ”模板文件名.“ TemplateDoc = C_T emplateDoc End Property Public Property Let TemplateDoc(ByVal vNewValue As String)C_TemplateDoc = vNewValue End Property Public Property Get newdoc()As String Attribute newdoc.VB_Description = ”执行CloseDoc方法时,将模板文件另存为此文件名指定的新文件.如果不指定,在执行CloseDoc方法时,将产生一个错误“ newdoc = C_newDoc End Property Public Property Let newdoc(ByVal vNewValue As String)C_newDoc = vNewValue End Property Public Property Get PicFile()As Str ing Attribute PicFile.VB_Description = ”图像文件名“ PicFile = C_PicFile End Property Public Property Let PicFile(ByVal vNewValue As String)C_PicFile = vNewValue End Property Public Property Get ErrMsg()As Integer Attribute ErrMsg.VB_Description = ”错误信息.ErrMsg代码: 1-word没有安装 2-缺少参数 3-没权限写文件 4-文件不存在“ ErrMsg = C_ErrMsg End Property 请问如何正确杀掉word进程?楼主btl19792008(btl19792008)2005-11-04 17:05:03 在 VB / 数据库(包含打印,安装,报表)提问我的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,使用它强大的查找、替换、删除、复制、翦切功能。
还可以把特定字符替换成图片。
有了它你就可以使用数据库中的内容或图片文件替换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进程。