VB调用WORD方法与实例代码
VBA中的集成与应用Word实例解析
VBA中的集成与应用Word实例解析VBA,即Visual Basic for Applications,是一种用于自动化操作Microsoft Office应用程序的编程语言。
在使用VBA时,与Word的集成和应用是非常常见的需求。
本文将从实例角度分析如何在VBA中实现Word的集成与应用。
首先,我们需要了解如何在VBA中引用和创建Word应用程序实例。
在VBA中,可以通过引用Microsoft Word的对象库来访问Word应用程序的各种功能。
下面是一个创建Word 应用程序实例的示例代码:```vbaDim wordApp As Word.ApplicationSet wordApp = New Word.Application```在上述代码中,我们首先声明一个Word应用程序对象的变量`wordApp`,然后使用`New`关键字创建一个新的Word应用程序实例,并将其赋值给变量`wordApp`。
接下来,我们可以在VBA中使用`wordApp`对象来操作Word应用程序的各种功能。
例如,我们可以打开一个现有的Word文档,或者创建一个新的Word文档。
下面是打开现有Word文档和创建新Word文档的示例代码:```vba' 打开现有的Word文档Dim wordDoc As Word.DocumentSet wordDoc =wordApp.Documents.Open("C:\Path\To\Existing.docx")' 创建新的Word文档Dim newDoc As Word.DocumentSet newDoc = wordApp.Documents.Add```在上述代码中,我们首先声明一个Word文档对象的变量`wordDoc`和`newDoc`,然后使用`Documents.Open`方法打开一个现有的Word文档,并将其赋值给变量`wordDoc`;使用`Documents.Add`方法创建一个新的Word文档,并将其赋值给变量`newDoc`。
vb操作word全
End WithEnd WithnewDoc.SaveAs filePathnewDoc.CloseEnd Function2、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种都不对。
网页或VB中操作word的方法
⽹页或VB中操作word的⽅法这段代码给我帮了很⼤的忙,希望他能帮到更多的⼈!1Public Function copy_mb(file1, file2path) As String2Dim fso As Object3Dim name4name = Date & ((Timer() - 0.0001)) * 100005Set fso = CreateObject("Scripting.FileSystemObject"[img]/images/wink.gif[/img]6Set f2 = fso.getfile(file1)7f2.Copy (file2path & name & ".doc"[img]/images/wink.gif[/img]8Set f2 = Nothing9Set fso = Nothing10copy_mb = file2path & name & ".doc"11End Function121314Public Function del_file(filename) As Boolean15Dim fso As Object16Set fso = CreateObject("Scripting.FileSystemObject"[img]/images/wink.gif[/img]17Set f2 = fso.getfile(filename)18f2.Delete19Set f2 = Nothing20Set fso = Nothing21End Function222324Public Function word_exe(filename, find_str, change_str) As String25Dim wdapp As New Word.Application26On Error GoTo e127Dim f_str() As String, c_str() As String, i As Integer28wdapp.Visible = True29wdapp.Documents.Open filename30f_str = Split(find_str, "|"[img]/images/wink.gif[/img]31c_str = Split(change_str, "|"[img]/images/wink.gif[/img]32For i = 0 To UBound(f_str)33If Len(c_str(i)) < 255 Then34wdapp.ActiveDocument.Content.Find.Execute f_str(i), , True, , , , , , , c_str(i), 235Else36Dim j As Integer, n As Integer37If (Len(c_str(i)) Mod (254 - Len(f_str(i)))) > 0 Then38 j = Int(Len(c_str(i)) / (254 - Len(f_str(i)))) + 139Else40 j = Int(Len(c_str(i)) / (254 - Len(f_str(i))))41End If4243For n = 1 To j44If n <> j Then45 wdapp.ActiveDocument.Content.Find.Execute f_str(i), , True, , , , , , , Mid(c_str(i), (n - 1) * (254 - Len(f_str(i))) + 1, 254 - Len(f_str(i))) & f_str(i), 246Else47 wdapp.ActiveDocument.Content.Find.Execute f_str(i), , True, , , , , , , Mid(c_str(i), (n - 1) * (254 - Len(f_str(i))) + 1, Len(c_str(i)) - (n - 1) * (254 - Len(f_s tr(i)))), 248End If49Next n50End If5152Next i5354wdapp.ActiveDocument.Save55wdapp.ActiveDocument.Close56wdapp.Quit5758Set wdapp = Nothing59word_exe = "OK"60Exit Function6162e1:63wdapp.Quit64Set wdapp = Nothing65Dim ErrMsg As String66ErrMsg = "Error Number:" & Err.Number & "<br><br>"67ErrMsg = ErrMsg & "Error Source:" & Err.Source & "<br><br>"68ErrMsg = ErrMsg & "Error Description:" & Err.Description & "<br><br>"69word_exe = ErrMsg70Exit Function7172End Function73747576Public Function open_word(filename)77Dim wdapp As New Word.Application78wdapp.Visible = True79wdapp.Documents.Open filename80End Function81828384Public Function copy_file(file1, file2, openstr) As String85Dim fso As Object86Set fso = CreateObject("Scripting.FileSystemObject"[img]/images/wink.gif[/img] 87Set f2 = fso.getfile(file1)88f2.Copy (file2)89Set f2 = Nothing90Set fso = Nothing91copy_file = file292If openstr = "yes" Then93Call open_word(file2)94End If95End Function96979899Public Function open_new(filename) As String100Dim wpsapp As New Word.Application101wpsapp.Documents.Add102wpsapp.Documents(1).SaveAs filename103wpsapp.Documents.Open filename104wpsapp.Visible = True105open_new = filename106End Function107108109110Public Function copy_content(filename) As String111Dim wdapp As New Word.Application112wdapp.Visible = False113wdapp.Documents.Open filename114wdapp.Selection.WholeStory115copy_content = wdapp.Selection.Text116wdapp.ActiveDocument.Close117wdapp.Quit118Set wdapp = Nothing119End Function120121122123Public Function copy_content2(filename) As String124Dim wdapp As New Word.Application125wdapp.Visible = False126wdapp.Documents.Open filename127wdapp.Selection.WholeStory128wdapp.Selection.Copy129copy_content2 = "已复制内容到剪贴板!!"130wdapp.ActiveDocument.Close131wdapp.Quit132Set wdapp = Nothing133End Function134135136137138Public Sub create_obj(a, b, c)139Dim obj As New WebFile140Call obj.HTTPPutFileEx(a, b, c)141Set obj = Nothing142End Sub143144145146Public Sub get_obj(a, b, c)147Dim obj As New WebFile148Call obj.HTTPGetFile(a, b, c)149End Sub150151152153154vbscript中的处理⽅法:155=========================================156157以下内容为程序代码:158159<script language="vbscript">160161On Error Resume Next162163Dim wApp164165Set wApp = CreateObject("Word.Application"[img]/images/wink.gif[/img] 166If Err.number > 0 Then167Alert "没法保存为Word⽂件,请正确安装Word软件"168else169wApp.visible = True170//.操作代码!171end if172173174。
用VB操作word方法.docx
1.'先引用Microsoft Word 11.0 Object Library2.Option Explicit3.4.Dim WordApp As Word.Application '创建Word应用程序5.6.Private Sub Command1_Click()7.Dim i As Long8.On Error GoTo Errhandler9. CommonDialog1.Filter = "Word(*.Doc)|*.Doc|AllFile(*.*)|*.*"10. CommonDialog1.FilterIndex = 111. CommonDialog1.ShowOpen12.Set WordApp = New Word.Application '实例化13. WordApp.Documents.Open CommonDialog1.FileName '打开Word文件14. WordApp.Visible = True'显示 Office Word 界面15.'或者Application.Visible = True16. WordApp.DisplayAlerts = False'不提示保存对话框17.18.'返回段落文字,返回的段落文字在文本框控件中19. Text1.Text = ""20.For i = 1 To ActiveDocument.Paragraphs.Count21. Text1.Text = Text1.Text & (ActiveDocument.Paragraphs(i).Range.Text &vbCrLf & vbCrLf)22.Next23.24.'控制分页25. WordApp.Selection.EndKey unit:=wdStory '将光标移到文档末尾26. WordApp.Selection.InsertBreak wdPageBreak '在文档末尾插入一页27.28.'设置图片格式的页眉29.If ActiveWindow.View.SplitSpecial <> wdPaneNone Then30. ActiveWindow.Panes(2).Close31.End If32.If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then33. ActiveWindow.ActivePane.View.Type = wdPrintView34.End If35. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader36. Selection.InlineShapes.AddPicture FileName:="F:\资料\My Pictures\2013年元旦.gif", LinkToFile:=False, SaveWithDocument:=True'加载一图片文件作为页眉37. Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft38. ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument39.40.'设置文本格式的页眉41.If ActiveWindow.View.SplitSpecial <> wdPaneNone Then42. ActiveWindow.Panes(2).Close43.End If44.If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then45. ActiveWindow.ActivePane.View.Type = wdPrintView46.End If47. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader48. Selection.TypeText Text:="办公室常用工具"49. ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument50.51.'隐藏页眉的横线52. WordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Borders(wdBorderBottom).Visible = False53.54.'取得页眉的内容55. Debug.Print WordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Text '获取WORD第一节的页眉的文字内容56.57.58.'设置页脚59.If ActiveWindow.View.SplitSpecial <> wdPaneNone Then60. ActiveWindow.Panes(2).Close61.End If62.If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then63. ActiveWindow.ActivePane.View.Type = wdPrintView64.End If65. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader66.If Selection.HeaderFooter.IsHeader = True Then67. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter68.Else69. ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader70.End If71. Selection.TypeText Text:="2013年"'设置页脚72. Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldNumPages73. ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument74.75. ActiveDocument.SaveAs "c:\MyWord.doc"'保存最后生成的word文档76.77.Errhandler:78.Exit Sub79.End Sub80.81.Private Sub Form_Unload(Cancel As Integer)82.On Error Resume Next83. WordApp.Quit84.Set WordApp = Nothing85.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. WordApp.Documents.Open CommonDialog1.FileName '打开Word文件13.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. WordApp.Selection.EndKey unit:=wdStory '将光标移到文档末尾21. WordApp.Selection.Font.Bold = 122. = "黑体"23. WordApp.Selection.Font.Size = 1824. WordApp.Selection.TypeText 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).TextFrame.TextRange.Text = "这是一个美女"'给文本框赋值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).TextFrame.TextRange.Text = "这是一个透明背景的文本框"'给文本框赋值42.'ActiveDocument.Shapes(2).Line.Transparency = 1 '设置透明边框线条43.44.'下面是获取文本框对象的内容45.Dim i As Long46.For i = 1 To ActiveDocument.Shapes.Count47. 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) '选择并打开Word文件15. 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效果图如下:。
VB轻松控制Word
VB轻松控制Word今天,我们将制作一个能够控制Word文件的建立和打开的应用程序。
我们可以在文本框中输入文件名,单击“新建”按钮即可新建一个Word文档,或者打开一个Word历史记录文件。
程序运行结果如图1所示。
图1 运行结果技术要点●添加Word库引用●建立Word对象●读取Word历史记录文件实现过程■新建项目打开Visual ,选择“新建项目”,在项目类型窗口中选择“Visual Basic项目”,在模板窗口中选择“Windows应用程序”,在名称域中输入“ControlWord”,然后选择保存路径。
单击“确认”。
■添加引用和控件选择菜单“项目|添加引用”,在弹出的“添加引用”对话框中选择COM选项卡,选中“Microsoft Word 10.0 Object Library”,单击“选择”按钮,即可将Word库加入到当前项目中。
添加时的界面如图2所示。
然后,给窗体上添加两个Label控件和两个Button控件,一个TextBox控件和一个ComboBox控件。
图2 添加Word引用■设置属性对窗体上的控件设置属性,如表所示。
窗体及控件的属性值窗体/控件属性值Form1 Text 轻松控制WordTextBox1 Text 空ComboBox Text 空Button1 Text 新建■添加代码Public Sub New()MyBase.New()'程序启动时,添加Word历史记录文件'This call is required by the Windows Form Designer.InitializeComponent()Dim i As ShortDim tempword As New Word.Application()For i = 1 To tempword.RecentFiles.CountComboBox1.Items.Add(tempword.RecentFiles.Item(i).Name)Next'ComboBox1.Text = ComboBox1.Items.IndexOf(ComboBox1).ToString'combobox1.Items.GetTytempword.Quit()'Add any initialization after the InitializeComponent() callEnd Sub'打开word文件Private Sub Button1_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles Button1.ClickDim b As New Word.Application()b.Documents.Open(ComboBox1.Text)b.Visible = TrueEnd Sub'新建word文件Private Sub Button2_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles Button2.ClickDim word As New Word.Application()word.NewDocument.Add(TextBox1.Text)word.Visible = TrueEnd Sub■运行程序单击菜单“调试|启动”或单击图标运行程序。
VB操作Word文档
VB创建,填充,预览,保存word文档的VB源代码Option Explicit’以下代码全部复制到VB标准模块中。
'word文档操作Private objApplication As Word.ApplicationPrivate objDocument As Word.DocumentPublic MyWordArray() As String '全局数组.'参数;strFilename 为模板文件的路径'功能;从一个模板文件创建一个新的word文档Public Function Create(ByVal strFilename As String) As BooleanSet objApplication = New Word.Application '一个新的word程序对象Set objDocument = objApplication.Documents.Add(strFilename)Create = TrueEnd Function入口参数;strFilename 是要保存的Word文件绝对路径值包含驱动器名称'保存文件Public Function Save(ByVal strFilename As String) As BooleanIf GFSO.FolderExists(App.Path & "\报表") = False ThenGFSO.CreateFolder App.Path & "\报表" '创建报表文件夹End IfobjDocument.SaveAs strFilenameSave = TrueEnd Function'功能;打印预览word文档Public Function Preview() As BooleanobjApplication.WindowState = wdWindowStateMaximizeobjApplication.Visible = TrueobjApplication.ActivateobjDocument.PrintPreviewPreview = TrueEnd Function'参数;strUnique 为指定的标志'参数;strValue 为替换的值'功能;替换word文档中指定的标志Public Function Find(ByVal strUnique As String, ByVal strValue As String) As Boolean Dim objFind As FindSet objFind = objDocument.Range.FindobjFind.Execute strUnique, , , , , , , , , strValue, wdReplaceAllFind = TrueEnd Function'入口参数;strFilename 为word文档的保存路径'功能;关闭word文档Public Function Quit(ByVal strFilename As String) As BooleanobjDocument.CloseobjApplication.Application.QuitSet objDocument = NothingSet objApplication = NothingQuit = TrueEnd Function'入口参数;MSHFA 是一个已填充数据的MSHF网格控件. '入口参数;Recordset_Array() 是一个全局数组用来存储经转换的二维数组'入口参数;RowValue 是指从那行开始转换为数组'功能;将MSHF网格中的数据转换为二维数组Public Function MSHF_to_Array(ByRef MSHFA As MSHFlexGrid, _ByRef MSHF_Array() As String, _ByVal RowValue As Long) As BooleanDim rows_value As Long '总行数Dim cols_value As Long '总列数Dim i As Long, j As Long '用于临时循环值.Dim rowindex As Long'找到总行数;For i = RowValue To MSHFA.Rows - 1rows_value = rows_value + 1Next'找到总列数;cols_value = MSHFA.Cols'为动态数组变量重新分配存储空间ReDim MSHF_Array(rows_value + 1, cols_value)'数组赋值For i = RowValue To MSHFA.Rows - 1For j = 0 To MSHFA.Cols - 1MSHF_Array(rowindex, j) = MSHFA.TextMatrix(i, j) & ""Nextrowindex = rowindex + 1NextMSHF_to_Array = TrueEnd Function'''参数;lngindex 为该表在该文档中的位置序号,从1开始'参数;strArray() 为要保存数据的二维数组.'功能;填充word文档中的表Public Function Fill(lngIndex As Long, ByRef strArray() As String) As Boolean Dim i As Long, j As LongDim objCell As Word.CellDim lngRows As LongFor i = 1 To UBound(strArray)'添加一行objDocument.Tables(lngIndex).Rows.Add'逐格填充数据For j = 1 To UBound(strArray, 2)lngRows = objDocument.Tables(lngIndex).Rows.CountSet objCell = objDocument.Tables(lngIndex).Rows(lngRows).Cells(j)objCell.Range.Text = strArray(i - 1, j - 1)NextNextSet objCell = NothingFill = TrueEnd Function’以下代码是窗体中调用代码范例。
怎样在VB中控制Word
怎样在VB中控制Word2001-09-19· ·--··vbeden使用VB编程时,有时需要调用Microsoft Word对文字进行编辑、排版及输出。
为实现这种调用,可以使用Shell函数、OLE自动化、在包容器中嵌入Word对象等方法。
经过试用和比较,总结出了这几种方法的各自特点。
1 使用Shell函数直接调用语法:Shell (pathname[,windowstyle]).Pathname是指要执行的程序的名字和任何必须的参数或命令行开关,可以包括目录和驱动器名;Windowstyle是执行程序的窗口风格的数字。
使用Shell调用Word比较简单,编程量小,但必须明确指定Word所在路径,这不利于移植,而且,不能对Word进行控制,不利于程序和Word之间的数据交换。
2 使用OLE自动化控制Microsoft Word2.1 使用方法(1)Word为OLE自动化提供一种称为“Basic”的对象,要在VB中控制Word ,首先要定义一个引用Word中“Basic”对象的对象变量:Dim Wordobj as Object(2)将Word 中的“Basic”对象赋给该对象:Set Wordobj=CreateObject("Word.Basic")(3)可以使用大多数WordBasic语句和函数控制Word或Word文档,使用方法和在Word宏中使用WordBasic指令的方法基本相同。
(4)关闭Word:Set Wordobj =Nothing。
注意:“Basic”对象不支持关闭它自己的一个方法。
即若在OLE自动化中关闭了Word,则对象被置为Nothing,便不能再对对象进行操作,程序出错。
2.2 VB指令与WordBasic指令的差异(1)有一些语句和函数不能使用,包括:控制结构,如While…Wend和If…Then…Else;声明语句,如Dim;定制对话框相关的语句:FileExit语句;要求数组变量作为参数的语句或函数。
VBNET操作word文档代码
操作WORD(VBA)操作WORD1Public Class WordOpLib234 Private oWordApplic As Word.ApplicationClass5 Private oDocument As Word.Document6 Private oRange As Word.Range7 Private oShape As Word.Shape8 Private oSelection As Word.Selection91011 Public Sub New()12 '激活com word接口13 oWordApplic = New Word.ApplicationClass14 oWordApplic.Visible = False1516 End Sub17 '设置选定文本18 Public Sub SetRange(ByVal para As Integer)19 oRange = oDocument.Paragraphs(para).Range20 oRange.Select()21 End Sub22 Public Sub SetRange(ByVal para As Integer, ByVal sent As Integer)23 oRange = oDocument.Paragraphs(para).Range.Sentences(sent)24 oRange.Select()25 End Sub26 Public Sub SetRange(ByVal startpoint As Integer, ByVal endpoint As Integer, ByVal flag As Boolean)27 If flag = True Then28 oRange = oDocument.Range(startpoint, endpoint)29 oRange.Select()30 Else3132 End If33 End Sub3435 '生成空的新文档36 Public Sub NewDocument()37 Dim missing = System.Reflection.Missing.Value38 Dim isVisible As Boolean = True39 oDocument = oWordApplic.Documents.Add(missing, missing, missing, missing)40 oDocument.Activate()41 End Sub42 '使用模板生成新文档43 Public Sub NewDocWithModel(ByVal FileName As String)44 Dim missing = System.Reflection.Missing.Value45 Dim isVisible As Boolean = False46 Dim strName As String47 strName = FileName48 oDocument = oWordApplic.Documents.Add(strName, missing, missing, isVisible)49 oDocument.Activate()50 End Sub51 '打开已有文档52 Public Sub OpenFile(ByVal FileName As String)53 Dim strName As String54 Dim isReadOnly As Boolean55 Dim isVisible As Boolean56 Dim missing = System.Reflection.Missing.Value5758 strName = FileName59 isReadOnly = False60 isVisible = True6162 oDocument = oWordApplic.Documents.Open(strName, missing, isReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing, missing)63 oDocument.Activate()6465 End Sub66 Public Sub OpenFile(ByVal FileName As String, ByVal isReadOnly As Boolean)67 Dim strName As String68 Dim isVisible As Boolean69 Dim missing = System.Reflection.Missing.Value7071 strName = FileName72 isVisible = True7374 oDocument = oWordApplic.Documents.Open(strName, missing, isReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing, missing)75 oDocument.Activate()76 End Sub77 '退出Word78 Public Sub Quit()79 Dim missing = System.Reflection.Missing.Value80 oWordApplic.Quit()81 System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic)82 oWordApplic = Nothing83 End Sub84 '关闭所有打开的文档85 Public Sub CloseAllDocuments()86 oWordApplic.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)87 End Sub88 '关闭当前的文档89 Public Sub CloseCurrentDocument()9091 oDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)92 End Sub93 '保存当前文档94 Public Sub Save()95 Try96 oDocument.Save()97 Catch98 MsgBox(Err.Description)99 End Try100 End Sub101 '另存为文档102 Public Sub SaveAs(ByVal FileName As String)103 Dim strName As String104 Dim missing = System.Reflection.Missing.Value105106 strName = FileName107108 oDocument.SaveAs(strName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)109 End Sub110 '保存为Html文件111 Public Sub SaveAsHtml(ByVal FileName As String)112 Dim missing = System.Reflection.Missing.Value113 Dim strName As String114115 strName = FileName116 Dim format = CInt(Word.WdSaveFormat.wdFormatHTML)117118 oDocument.SaveAs(strName, format, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)119 End Sub120 '插入文本121 Public Sub InsertText(ByVal text As String)122 oWordApplic.Selection.TypeText(text)123 End Sub124 '插入一个空行125 Public Sub InsertLineBreak()126 oWordApplic.Selection.TypeParagraph()127 End Sub128 '插入指定行数的空行129 Public Sub InsertLineBreak(ByVal lines As Integer)130 Dim i As Integer131 For i = 1 To lines132 oWordApplic.Selection.TypeParagraph()133 Next134 End Sub135 '插入表格136 Public Sub InsertTable(ByRef table As DataTable)137 Dim oTable As Word.Table138 Dim rowIndex, colIndex, NumRows, NumColumns As Integer139 rowIndex = 1140 colIndex = 0141 If (table.Rows.Count = 0) Then142 Exit Sub143 End If144145 NumRows = table.Rows.Count + 1146 NumColumns = table.Columns.Count147 oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows, NumColumns)148149150 '初始化列151 Dim Row As DataRow152 Dim Col As DataColumn153 'For Each Col In table.Columns154 ' colIndex = colIndex + 1155 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)156 'Next157158 '将行添入表格159 For Each Row In table.Rows160 rowIndex = rowIndex + 1161 colIndex = 0162 For Each Col In table.Columns163 colIndex = colIndex + 1164 oTable.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))165 Next166 Next167 oTable.Rows(1).Delete()168 oTable.AllowAutoFit = True169 oTable.ApplyStyleFirstColumn = True170 oTable.ApplyStyleHeadingRows = True171172 End Sub173 '插入表格(修改为在原有表格的基础上添加数据)174 Public Sub InsertTable2(ByRef table As DataTable, ByVal strbmerge As String, ByVal totalrow As Integer)175 Dim oTable As Word.Table176 Dim rowIndex, colIndex, NumRows, NumColumns As Integer177 Dim strm() As String178 Dim i As Integer179 rowIndex = 1180 colIndex = 0181182 If (table.Rows.Count = 0) Then183 Exit Sub184 End If185186 NumRows = table.Rows.Count + 1187 NumColumns = table.Columns.Count188 'oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows, NumColumns)189190191 '初始化列192 Dim Row As DataRow193 Dim Col As DataColumn194 'For Each Col In table.Columns195 ' colIndex = colIndex + 1196 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)197 'Next198199 '将行添入表格200 For Each Row In table.Rows201 colIndex = 0202 GotoRightCell()203 oWordApplic.Selection.InsertRows(1)204 For Each Col In table.Columns205 GotoRightCell()206 colIndex = colIndex + 1207 Try208 oWordApplic.Selection.TypeText(Row(Col.ColumnName))209 Catch ex As Exception210 oWordApplic.Selection.TypeText(" ")211 End Try212 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))213 Next214 Next215 '如果strbmerge不为空.则要合并相应的行和列216 If strbmerge.Trim().Length <> 0 Then217 strm = strbmerge.Split(";")218 For i = 1 To strm.Length - 1219 If strm(i).Split(",").Length = 2 Then220 MergeDouble(totalrow, strm(0), strm(i).Split(",")(1), strm(i).Split(",")(0))221 End If222 MergeSingle(totalrow, strm(0), strm(i))223 Next224 End If225 '删除可能多余的一行226 'GotoRightCell()227 'GotoDownCell()228 'oWordApplic.Selection.Rows.Delete()229 'oTable.AllowAutoFit = True230 'oTable.ApplyStyleFirstColumn = True231 'oTable.ApplyStyleHeadingRows = True232 End Sub233 '插入表格(专门适应工程结算工程量清单)234 Public Sub InsertTableQD(ByRef table As DataTable, ByRef table1 As DataTable)235 Dim oTable As Word.Table236 Dim rowIndex, colIndex, NumRows, NumColumns As Integer237 Dim xmmc As String238 Dim i As Integer239 Dim j As Integer240 rowIndex = 1241 colIndex = 0242243 If (table.Rows.Count = 0) Then244 Exit Sub245 End If246247 NumRows = table.Rows.Count + 1248 NumColumns = table.Columns.Count249 'oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows,NumColumns)250251252 '初始化列253 Dim Row As DataRow254 Dim rowtemp As DataRow255 Dim row1() As DataRow256 Dim Col As DataColumn257 Dim coltemp As DataColumn258 'For Each Col In table.Columns259 ' colIndex = colIndex + 1260 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)261 'Next262263 '将行添入表格264 For Each Row In table.Rows265 colIndex = 0266 xmmc = Row("项目名称")267 GotoRightCell()268 oWordApplic.Selection.InsertRows(1)269 For Each Col In table.Columns270 GotoRightCell()271 Try272 If (Col.ColumnName = "项目序号") Then273oWordApplic.Selection.TypeText(intToUpint(Val(Row(Col.ColumnName))))274 Else275 oWordApplic.Selection.TypeText(Row(Col.ColumnName))276 End If277 Catch ex As Exception278 oWordApplic.Selection.TypeText(" ")279 End Try280 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))281 Next282 row1 = table1.Select("项目名称='" + xmmc + "'")283284 For i = 0 To row1.Length - 1285 GotoRightCell()286 oWordApplic.Selection.InsertRows(1)287 For j = 0 To table1.Columns.Count - 1288 If (table1.Columns(j).ColumnName <> "项目名称") Then289 GotoRightCell()290 Try291 oWordApplic.Selection.TypeText(row1(i)(j))292 Catch ex As Exception293 oWordApplic.Selection.TypeText(" ")294 End Try295 End If296 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))297 Next298 Next299300301302 Next303 '删除可能多余的一行304 'GotoRightCell()305 'GotoDownCell()306 'oWordApplic.Selection.Rows.Delete()307 'oTable.AllowAutoFit = True308 'oTable.ApplyStyleFirstColumn = True309 'oTable.ApplyStyleHeadingRows = True310 End Sub311 '插入表格,为了满足要求,在中间添加一根竖线312 Public Sub InsertTable3(ByRef table As DataTable, ByVal introw As Integer, ByVal intcol As Integer)313 Dim rowIndex, colIndex, NumRows, NumColumns As Integer314 Dim Row As DataRow315 Dim Col As DataColumn316 If (table.Rows.Count = 0) Then317 Exit Sub318 End If319 '首先是拆分选中的单元格320 oDocument.Tables(1).Cell(introw, 3).Split(table.Rows.Count, 2)321 '选中初始的单元格322 oDocument.Tables(1).Cell(introw, 3).Select()323 '将行添入表格324 For Each Row In table.Rows325 Try326 oDocument.Tables(1).Cell(introw, 3).Range.InsertAfter(Row(0))327 oDocument.Tables(1).Cell(introw, 4).Range.InsertAfter(Row(1))328 Catch ex As Exception329 oDocument.Tables(1).Cell(introw, 3).Range.InsertAfter(" ")330 oDocument.Tables(1).Cell(introw, 4).Range.InsertAfter(" ")331 End Try332 introw = introw + 1333 Next334 End Sub335 '设置对齐336 Public Sub SetAlignment(ByVal strType As String)337 Select Case strType338 Case "center"339 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter340 Case "left"341 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft342 Case "right"343 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight344 Case "justify"345 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify346 End Select347 End Sub348 '设置字体349 Public Sub SetStyle(ByVal strFont As String)350 Select Case strFont351 Case "bold"352 oWordApplic.Selection.Font.Bold = 1353 Case "italic"354 oWordApplic.Selection.Font.Italic = 1355 Case "underlined"356 oWordApplic.Selection.Font.Subscript = 1357 End Select358 End Sub359 '取消字体风格360 Public Sub DissableStyle()361 oWordApplic.Selection.Font.Bold = 0362 oWordApplic.Selection.Font.Italic = 0363 oWordApplic.Selection.Font.Subscript = 0364 End Sub365 '设置字体字号366 Public Sub SetFontSize(ByVal nSize As Integer)367 oWordApplic.Selection.Font.Size = nSize368 End Sub369 '跳过本页370 Public Sub InsertPageBreak()371 Dim pBreak As Integer372 pBreak = CInt(Word.WdBreakType.wdPageBreak)373 oWordApplic.Selection.InsertBreak(pBreak)374 End Sub375 '转到书签376 Public Sub GotoBookMark(ByVal strBookMark As String)377 Dim missing = System.Reflection.Missing.Value378 Dim BookMark = CInt(Word.WdGoToItem.wdGoToBookmark)379 oWordApplic.Selection.GoTo(BookMark, missing, missing, strBookMark)380 End Sub381 '判断书签是否存在382 Public Function BookMarkExist(ByVal strBookMark As String) As Boolean383 Dim Exist As Boolean384 Exist = oDocument.Bookmarks.Exists(strBookMark)385 Return Exist386 End Function387 '替换书签的内容388 Public Sub ReplaceBookMark(ByVal icurnum As String, ByVal strcontent As String) 389 strcontent = strcontent.Replace("0:00:00", "")390 oDocument.Bookmarks(icurnum).Select()391 oWordApplic.Selection.TypeText(strcontent)392 End Sub393394 '得到书签的名称395 Public Function GetBookMark(ByVal icurnum As String, ByRef bo As Boolean) As String 396 Dim strReturn As String397 If Right(oDocument.Bookmarks(icurnum).Name, 5) = "TABLE" Then398 bo = True399 Dim strTemp As String400 strTemp = oDocument.Bookmarks(icurnum).Name()401 strReturn = Mid(strTemp, 1, Len(strTemp) - 5)402 Else403 bo = False404 strReturn = oDocument.Bookmarks(icurnum).Name405 End If406 Return strReturn407 End Function408 '得到书签的名称409 Public Function GetBookMark1(ByVal icurnum As String) As String410 Return oDocument.Bookmarks(icurnum).Name411 End Function412 '转到文档结尾413 Public Sub GotoTheEnd()414 Dim missing = System.Reflection.Missing.Value415 Dim unit = Word.WdUnits.wdStory416 oWordApplic.Selection.EndKey(unit, missing)417 End Sub418 '转到文档开头419 Public Sub GotoTheBegining()420 Dim missing = System.Reflection.Missing.Value421 Dim unit = Word.WdUnits.wdStory422 oWordApplic.Selection.HomeKey(unit, missing)423 End Sub424 '删除多余的一行425 Public Sub DelUnuseRow()426 oWordApplic.Selection.Rows.Delete()427 End Sub428 '转到表格429 Public Sub GotoTheTable(ByVal ntable As Integer)430 'Dim missing = System.Reflection.Missing.Value431 'Dim what = Word.WdGoToItem.wdGoToTable432 'Dim which = Word.WdGoToDirection.wdGoToFirst433 'Dim count = ntable434435 'oWordApplic.Selection.GoTo(what, which, count, missing)436 'oWordApplic.Selection.ClearFormatting()437438 'oWordApplic.Selection.Text = ""439 oRange = oDocument.Tables(ntable).Cell(1, 1).Range440 oRange.Select()441442 End Sub443 '转到表格的某个单元格444 Public Sub GotoTableCell(ByVal ntable As Integer, ByVal nRow As Integer, ByVal nColumn As Integer)445 oRange = oDocument.Tables(ntable).Cell(nRow, nColumn).Range446 oRange.Select()447 End Sub448 '表格中转到右面的单元格449 Public Sub GotoRightCell()450 Dim missing = System.Reflection.Missing.Value451 Dim direction = Word.WdUnits.wdCell452 oWordApplic.Selection.MoveRight(direction, missing, missing)453 End Sub454 '表格中转到左面的单元格455 Public Sub GotoLeftCell()456 Dim missing = System.Reflection.Missing.Value457 Dim direction = Word.WdUnits.wdCell458 oWordApplic.Selection.MoveLeft(direction, missing, missing)459 End Sub460 '表格中转到下面的单元格461 Public Sub GotoDownCell()462 Dim missing = System.Reflection.Missing.Value463 Dim direction = Word.WdUnits.wdCell464 oWordApplic.Selection.MoveDown(direction, missing, missing)465 End Sub466 '表格中转到上面的单元格467 Public Sub GotoUpCell()468 Dim missing = System.Reflection.Missing.Value469 Dim direction = Word.WdUnits.wdCell470 oWordApplic.Selection.MoveUp(direction, missing, missing)471 End Sub472 '文档中所有的书签总数473 Public Function TotalBkM() As Integer474 Return oDocument.Bookmarks.Count475 End Function476 '选中书签477 Public Sub SelectBkMk(ByVal strName As String)478 oDocument.Bookmarks.Item(strName).Select()479 End Sub480 '插入图片481 Public Sub InsertPic(ByVal FileName As String)482 Dim missing = System.Reflection.Missing.Value483 oWordApplic.Selection.InlineShapes.AddPicture(FileName, False, True, missing).Select()484 oShape = oWordApplic.Selection.InlineShapes(1).ConvertToShape485 oWordApplic.Selection.WholeStory()486 oShape.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendBehindText)487 End Sub488 '统一调整图片的位置.也就是往上面调整图片一半的高度489 Public Sub SetCurPicHei()490 Dim e As Word.Shape491 For Each e In oDocument.Shapes492 oDocument.Shapes().Select()493 oWordApplic.Selection.ShapeRange.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage494 oWordApplic.Selection.ShapeRange.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionParagraph495 oWordApplic.Selection.ShapeRange.LockAnchor = True496'oWordApplic.Selection.ShapeRange.IncrementTop(oDocument.Shapes().Height)497 Next498 End Sub499500 Public Sub SetCurPicHei1()501 Dim e As Word.Shape502 For Each e In oDocument.Shapes503 oDocument.Shapes().Select()504oWordApplic.Selection.ShapeRange.IncrementTop(oDocument.Shapes().Height / 2)505 Next506 End Sub507 Public Sub SetCurPicHei2()508 Dim e As Word.Shape509 For Each e In oDocument.Shapes510 oDocument.Shapes().Select()511oWordApplic.Selection.ShapeRange.IncrementTop(-oDocument.Shapes().Height / 2)512 Next513 End Sub514 Public Function intToUpint(ByVal a As Integer) As String515 Dim result As String = "一百"516 Dim a1, a2 As Integer517 Dim strs() As String = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"} 518 If (a <= 10) Then519 result = strs(a)520 ElseIf (a < 100) Then521 a1 = a / 10522 a2 = a Mod 10523 If (a = 1) Then524 result = "十" + strs(a2)525 End If526 Else527 result = strs(a1) + "十" + strs(a2)528 End If529 Return result530 End Function531 '合并没有参照的某一列,一般来讲对应第一列532 'itotalrow 总行数533 'initrow 初始开始的行数,一般情况下该值不为0,没有标题栏的一般为0534 'intcol 列数535 Public Sub MergeSingle(ByVal itotalrow As Integer, ByVal initrow As Integer, ByVal intcol As Integer)536 oDocument.Tables(1).Cell(initrow + 1, intcol).Select()537 Dim irow As Integer '当前行数538 Dim strValue As String '循环比较的行初值539 Dim i As Integer540 Dim direction = Word.WdUnits.wdLine541 Dim extend = Word.WdMovementType.wdExtend542543 i = 0544 irow = 1 + initrow '初始值为1545 For i = 2 + initrow To itotalrow + initrow546547 strValue = oDocument.Tables(1).Cell(irow, intcol).Range.Text548 If (oDocument.Tables(1).Cell(i, intcol).Range.Text = oDocument.Tables(1).Cell(irow, intcol).Range.Text) Then549 '这是对最后一次处理的特殊情况.550 If (i = itotalrow + initrow) Then551 oWordApplic.Selection.MoveDown(direction, (i - irow), extend)552 If (i - irow >= 1) Then553 oWordApplic.Selection.Cells.Merge()554 End If555 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue556 End If557 Else558 oWordApplic.Selection.MoveDown(direction, (i - irow - 1), extend)559 If (i - irow - 1 >= 1) Then560 oWordApplic.Selection.Cells.Merge()561 End If562 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue563 irow = i564 oDocument.Tables(1).Cell(irow, intcol).Select()565 End If566 Next i567 End Sub568 '合并有参照的某一列569 'itotalrow 总行数570 'initrow 初始开始的行数,一般情况下该值不为0,没有标题栏的一般为0571 'intcol 列数572 'basecol 参照合并的那一列573 Public Sub MergeDouble(ByVal itotalrow As Integer, ByVal initrow As Integer, ByVal intcol As Integer, ByVal basecol As Integer)574 oDocument.Tables(1).Cell(initrow + 1, intcol).Select()575 Dim irow As Integer '当前行数576 Dim strValue As String '循环比较的行初值577 Dim i As Integer578 Dim direction = Word.WdUnits.wdLine579 Dim extend = Word.WdMovementType.wdExtend580581 i = 0582 irow = 1 + initrow '初始值为1583 For i = 2 + initrow To itotalrow + initrow584585 strValue = oDocument.Tables(1).Cell(irow, intcol).Range.Text586 If (oDocument.Tables(1).Cell(i, intcol).Range.Text = oDocument.Tables(1).Cell(irow, intcol).Range.Text) And (getdata(i, basecol) = getdata(irow, basecol)) Then587 '这是对最后一次处理的特殊情况.588 If (i = itotalrow + initrow) Then589 oWordApplic.Selection.MoveDown(direction, (i - irow), extend)590 If (i - irow >= 1) Then591 oWordApplic.Selection.Cells.Merge()592 End If593 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue594 End If595 Else596 oWordApplic.Selection.MoveDown(direction, (i - irow - 1), extend)597 If (i - irow - 1 >= 1) Then598 oWordApplic.Selection.Cells.Merge()599 End If600 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue601 irow = i602 oDocument.Tables(1).Cell(irow, intcol).Select()603 End If604 Next i605 End Sub606 '得到某个单元的值,如果为空的话,有两种情况.607 '其一:是一个合并的单元格,取其上面的值608 '其二:该单元格本来就是空值609 Public Function getdata(ByVal introw As Integer, ByVal intcol As Integer) As String610 Try611 If (oDocument.Tables(1).Cell(introw, intcol).Range.Text = "" Or (oDocument.Tables(1).Cell(introw, intcol).Range.Text = Nothing)) Then612 getdata = getdata(introw - 1, intcol)613 Else614 getdata = oDocument.Tables(1).Cell(introw, intcol).Range.Text615 End If616 Catch ex As Exception617 getdata = getdata(introw - 1, intcol)618 End Try619620621 End Function622End Class要想作为一个优秀的编程人员,不得不每天都进行学习,来增加自己的知识库,以免被技术所淘汰。
VB操作WORD详解
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应用程序后,需要关闭它以释放系统资源。
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 - 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,使用它强大的查找、替换、删除、复制、翦切功能。
如何在 VBA 中操作 Word 文档
如何在 VBA 中操作 Word 文档VBA(Visual Basic for Applications)作为一种用于自动化任务的编程语言,与Microsoft Office套件紧密结合,使用户能够使用宏和脚本来对Office应用程序进行编程操作。
在本文中,我们将重点介绍如何使用VBA来操作Word文档。
1. 创建和打开Word文档在VBA中,可以使用Application对象来创建和打开Word 文档。
下面是创建一个新文档和打开一个已存在的文档的示例代码:```vbaSub CreateAndOpenDocument()Dim WordApp As Object ' 创建一个Word应用程序对象Set WordApp = CreateObject("Word.Application")Dim WordDoc As Object ' 创建一个新文档Set WordDoc = WordApp.Documents.Add' 打开一个已存在的文档WordApp.Documents.Open("C:\Path\To\Your\Document.docx") ' 执行其他操作...' 关闭Word应用程序对象WordApp.QuitEnd Sub```2. 插入和编辑文本在Word文档中插入和编辑文本是VBA中的常见操作。
要在文档中插入文本,可以使用Selection对象的TypeText方法,如下所示:```vbaSub InsertText()Selection.TypeText Text:="这是要插入的文本。
"End Sub```要编辑已存在的文本,可以使用Selection对象的Text属性来访问和修改文本内容,如下所示:```vbaSub EditText()Selection.Text = "这是修改后的文本。
[VIP专享]vb操作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做一个模板,把表格什么的全都先写好,然后保存成模板文件。
教你如何以VB对word 文件进行读写操作
VB6.0 如何对word 文件进行读写操作•对于这样的表格我通过下面一段代码可以实现,但如何对图二最下面的内容进行填充谢谢啦Set WordObj = CreateObject("Word.Application")WordObj.Visible = FalseIf wordfilepath = "" ThenMsgBox "请先打开文件!"Exit SubEnd IfSet myword = WordObj.Documents.Open(wordfilepath)strText = ActiveDocument.Words(1).Text'ActiveDocument.Words(1).Text = "Hello"With myword.Tables(1) .Cell(7, 2).Range.Text = "22"End Withmyword.CloseWordObj.Quit图一图二•百度下很多的,下面是我以前用的方法,要样板首先在要修改的word样板中要修改的地方随便写几个字(我写的是标记)作为标志,然后选中这些字,点工具插入mark,记住你起的名字(我起的是标记),然后参考以下代码。
Dim wd As New Word.ApplicationDim doc As Word.Documentwd.Visible = FalseSet doc = wd.Documents.Add(App.Path & "\样板.doc") '当模板用add,否则用open doc.Bookmarks("标记").Range.Text = "这里写你要输入的文字"doc.SaveAs "样板1.doc"doc.Closewd.Quit。
VB千里行-操作Word与Excel
文将告诉你如何使用VB代码连接Office应用程序,并简要接触一下在文件中输入数据的方法。
实际上,在VB中用代码与Word和Excel进行会话并控制它们,是可行的。
但是请注意,首先需要在机器上安装office应用程序,才能在VB代码中存取它们的对象。
下面就是一些例子,告诉你如何与这些程序会话,并控制它们。
Option ExplicitDim xlsApp As Excel.ApplicationDim wrdApp As Word.Application只要相关的对象库已经被选择,在应用程序中进行对象变量的赋值是可能的。
Microsoft Excel 8.0对象库是相对于Excel的,而 Microsoft Word 8.0 对象库是为Word服务的。
在VB的IDE环境中,从“工程”菜单中选择“引用”,可以看到系统可用的所有库列表。
Private Sub Command1_Click()Set xlsApp = Excel.ApplicationWith xlsApp´Show Excel.Visible = True´Create a new workbook.Workbooks.Add´Put text in to the cell that is selected.ActiveCell.Value = "Hi"´Put text into A3 regardless of the selected cell.Range("A3").Value = "This is an example of connecting to Excel" End WithEnd Sub在上面的程序段中,我们在变量xlsApp中建立了一个对象,这样Excel就对用户可见了。
当Excel象这样启动后,并不包含一个工作簿,所以必须创建或者执行打开操作。
VBA在Word中的使用方法详解
VBA在Word中的使用方法详解在现代科技发展的时代背景下,VBA(Visual Basic for Applications)语言是一个强大的自动化脚本语言,可以用来增强Word文档的功能和自动化一些重复性的任务。
本文将详细介绍VBA在Word中的使用方法,帮助读者快速上手。
一、VBA入门1. 启用开发者选项:在Word中,首先要启用开发者选项,可通过点击"文件"->"选项"->"自定义功能区"来启用开发者选项。
2. 打开Visual Basic编辑器:在开发者选项中,点击"Visual Basic"按钮即可打开Visual Basic编辑器。
3. 新建VBA模块:在Visual Basic编辑器中,点击"插入"->"模块",即可新建一个VBA模块。
二、常用的VBA操作方法1. 宏录制:Word的宏录制功能可以帮助我们快速录制鼠标和键盘的操作,将其转化为VBA代码。
点击"开发者"->"宏录制",录制你需要的操作即可。
录制结束后,可以在Visual Basic编辑器中看到所生成的VBA代码。
2. VBA代码编辑:在VBA代码编辑器中,可以直接编写VBA代码来实现自定义的功能。
以下是一些常用的VBA操作方法:a. 文字处理:可以使用VBA来进行文字的查找、替换和格式修改。
例如,通过VBA代码可以实现批量替换文档中的某个词语。
b. 文档生成:VBA可以帮助我们自动生成文档,并进行格式设置和内容处理。
例如,可以利用VBA代码自动生成报告或合同。
c. 表格操作:VBA可以对Word中的表格进行自动化操作,包括添加、删除、格式修改等。
例如,可以通过VBA代码自动创建表格,并设置表格样式。
d. 图像处理:VBA可以帮助我们对Word文档中的图片进行处理,如插入、删除、修改大小和位置等。
VB操作word总结
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进程。
VB调用WORD方法与实例代码
VB调用WORD方法与实例代码'=============打开word==============Function OpenWord(FileName)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'===================用VB调用WORD代码============Private Sub Form_Load()Dim wp As New Word.ApplicationDim wd As New Word.Documentwp.Visible = TrueSet wd = wp.Documents.Open("c:\22075847937.doc")Dim neirong As Stringneirong = wd.Content.TextMsgBox "该Word文件的内容为:" & vbNewLine & neirong End Sub。
VB。net调用Word
写word文件代码:Dim wordApp As New Word.ApplicationDim objSelection As Word.SelectionDim Title As String = "K388+400常胜沟大桥"wordApp.Documents.Add()oDocument = wordApp.ActiveDocumentobjSelection = wordApp.SelectionwordApp.Selection.TypeText(Title)objSelection.TypeParagraph()wordApp.Selection.TypeText("一、桥梁基本状况卡片")objSelection.TypeParagraph()wordApp.Selection.TypeText("A行政数据识别,B技术结构数据")objSelection.TypeParagraph()wordApp.Selection.TypeText("A行政数据识别。
B技术结构数据。
C档案资料(全、不全、或无)。
D最近技术状况评定")objSelection.InsertBreak() '插入分页符,相当于2个字符objSelection.TypeText("E修建工程记录")SetRange(1)With wordApp.Selection.Font.Size = 18 '字体(小二).ParagraphFormat.Alignment = 1 '水平居中.Font.Bold = TrueEnd WithSetRange(2)With wordApp.Selection.Font.Size = 14 '字体(四).Font.Bold = True = "华文琥珀"End WithSetRange(25, 44, True)With wordApp.Selection.Font.Size = 9 '字体(小五).Font.Bold = True.Font.Italic = TrueEnd WithSetRange(4, 2)With wordApp.Selection.Font.Size = 9 '字体(小五).Font.Bold = TrueEnd With'文件保存oDocument.SaveAs("d:\" & Title & ".doc") wordApp.Visible = True。
vbaword基本操作(经典)
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 & "/" & filename1 End 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中的内容的回车和换⾏都替换为空。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
'=============打开word==============
FunctAs New Word.Application
Dim wordDoc As New Word.Document
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = False
Set wordDoc = wordApp.Documents.Open(FileName)
End Function
'============替换关键字===========
Function ReplaceWord(SearchStr, ReplaceStr)
Dim wd As New Word.Document
wp.Visible = True
Set wd = wp.Documents.Open("c:\22075847937.doc")
Dim neirong As String
neirong = wd.Content.Text
End Function
'============另存为===================
Function SaveAsWord(DiskStr, NameStr)
ChangeFileOpenDirectory DiskStr
ActiveDocument.SaveAs FileName:=NameStr, FileFormat:=wdFormatDocument, _
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = SearchStr
.Replacement.Text = ReplaceStr
MsgBox "该Word文件的内容为:" & vbNewLine & neirong
End Sub
Set wordApp = Nothing '清除WORD实例
End Function
'===================用VB调用WORD代码============
Private Sub Form_Load()
Dim wp As New Word.Application
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Application.Documents.Close
Application.Quit
End Function
'===================清除对象============
Function CloseWord()
Set wordDoc = Nothing '清除文件实例
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= False