ExcelVBA操作Word(⼊门篇)
本⽂的对象是:有⼀定Excel VBA基础,对Word VBA还没有什么认识,想在Excel中通过VBA操作Word还有困难的⼈。
⼀、新建Word引⽤
需要⾸先创建⼀个对 Word Application 对象的引⽤。在VBA中,⼯具-引⽤,选取“MicroSoft Word 11.0 Object Library”。
⽅法⼀、New Word.Application
Dim Wordapp As Word.Application
Set Wordapp = NewWord.Application
Wordapp.Visible = True                    '可见
'Wordapp.ScreenUpdating =False            '屏幕刷新
Dim WordD As Word.Document      '定义word类
Set WordD = Wordapp.Documents.Add                  '新建⽂档
'Set WordD = Wordapp.Documents.open(filename)          '打开⽂档
'……
WordD.Close                        '关闭⽂档
Set WordD = Nothing
WordApp.Quit                        '退出Word对象
⽅法⼆、CreateObject
Dim WordApp As Object
Set WordApp =CreateObject("Word.Application")    '新建Word对象
‘后续操作及退出⼀样……
⽅法三、GetObject
⽂件已打开的情况下,使⽤:SetWordD=GetObject(filename),可建⽴对⽂档的引⽤,如果⽂件没有打开,则还需要先⽤⽅法⼀或⼆来操作。
⾄于⽅法⼀和⽅法⼆的区别,在⽹上询问了⼀下,⼤师们的回答是:
⽅法⼀:前期绑定,好处是在对象后输⼊句点可以给出快速提⽰,因为需要先引⽤对象,所以容易出现版本兼容问题。
⽅法⼆:后期绑定,没有提⽰,根据运⾏代码机器上对象的版本创建对象,兼容性好。
提⽰:有时⼆者有较⼤区别,可论坛搜索字典对象,建议编写代码时使⽤前期绑定,发布时使⽤后期绑定。
⼆、认识Word的结构
Excel有:
Excel.Application                        ’Excel引⽤
Excel.Application. Workbooks            ’⼯作簿
Excel.Application. Workbooks.Sheets(1)      ’⼯作表
⼯作表下是Range,区域;Cells(row,col),单元格
Word有:
Word.Application
Word.Application.Documents          ’⽂档
⽂档下有字符、单词、句⼦、段落和节。字符组成单词,单词组成句⼦,句⼦组成段落。此外,每个⽂档具有⼀个包含⼀个或多个节的Sections 集合,每⼀个节都有⼀个包含该节页眉和页脚的HeadersFooters 集合。
Characters(index)
Words(index)
Sentences(index)
Paragraphs(index)
Sections(index)
前三个返回Range对象,能直接使⽤任何区域属性或⽅法修改该Range 对象。后⾯⼆个返回该集合的单个成员,⽽不是 Range 对象,不能直接使⽤区域属性或⽅法。如下使⽤例⼦:Words(1)后⾯直接.Copy,⽽.Paragraphs(1)和.Copy之间多了⼀个Range。
Selection.Words(1).Copy
ActiveDocument.Paragraphs(1).Range.Copy
Characters:字符,ActiveDocument.Sentences(1).Characters.Count,第⼀句的字符总数。
Words:单词,对于英⽂来说是⼆个空格之间的字母加空格,对于中⽂,⼀个标点符号,⼀个汉字,或⼀个词(按照微软的输⼊法中的词组定义?)。(感觉不是很可靠?)
Sentences:句⼦,以句号结束?感觉也不是⼀个很可靠的范围,感觉还是字符、段落、节,控制起来靠谱⼀些。
Range 对象表⽰⽂档中的⼀个连续范围,由⼀个起始字符位置和⼀个终⽌字符位置定义。这个连续范围可以⼩到⼀个插⼊点,⼤到整个⽂档。
Dim rngPa As Range
Set rngPa =ActiveDocument. Characters (1)    '第⼀个字符
Set rngPa = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(1).Range.Start, _
End:=ActiveDocument.Paragraphs(4).Range.End)            ‘第1段头到第4段尾
Set rngPa = ActiveDocument.Range(Start:=0,End:=10)    ‘当前⽂档前10个字符
rngPa.Select
选定,我觉得⽤处不⼤,原因就是为什么要选中呢?能操作就直接操作,不能的话,就选中吧(他可以说是没办法的办法)。
range对象的赋值:(包括任意的对象,Set是对对象赋值的标准语句)
set a=b
和变量的赋值:a=1不⼀样
第三段:通过录制宏⽣成代码,修改如下:
三、通过录制宏⽣成代码
有了对Word基本结构的认识,想操作这些对象应该使⽤什么⽅法、修改哪些属性?不知道就“录制宏”。录制宏是我们认识未知对象的很好⽅法之⼀,通过宏录制器将操作译成Word的 Visual Basic 代码,再根据需要修改代码。Word中录制与Excel不同的是,不能使⽤⿏标移动光标或选中⼀⾏,只能使⽤键盘来移动,或⽤Shift+⽅向键来选中。以下⼏句话就是键盘的:上、下、左、右、Home、End、Shift+左选中5个字符、Shift+右选中5个字符。
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine
Selection.MoveLeft Unit:=wdCharacter, Count:=5, Extend:=wdExtend
Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
录制的宏使⽤ Selection 属性返回 Selection 对象。即:录制的宏总是以Selection.开头的,如上。要想使⽤这个Selection.,有时候我们就不得不先对特定的对象.Select,选中。
当然,Selection是⼀个Range,Characters、Words、Sentences也是Range,Paragraphs(n). Range, Sections(2). Range也是Range,那我们就可以将Selection.后⾯的语句嫁接到前⾯这些Range之后,就不⽤先.Select了。
录制的宏,通过嫁接或者复制到EXCEL VBA之后,有的运⾏会出错,此时应检查以下⼏项:
1、第⼀项中要求的“引⽤”建⽴了没?
2、利⽤VBA提醒功能检查语句。VBA编辑过程中,通常在打下. 之后(需要前期绑定?),该对象所有的⽅法、属性都会显⽰出来,利⽤这个特点,可以检查录制的宏,能否嫁接到需要操作的对象之后。提⽰⾥有就能,没有就不能。
3、部分转换函数,Word VBA⾥有,Excel VBA⾥可能没有,遇到这样的情况,也可能出错。
例:
WordD.Paragraphs(1).Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.35)
Selection.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.35)是“⾸⾏缩进2字符”操作录制的,嫁接后,运⾏出错,按⽅法2检查:.ParagraphFormat.FirstLineIndent能⽤在Range之后,那么就是CentimetersToPoints(0.35)出问题了?这显然是⼀个函数,字⾯意思
是“厘⽶转换成点数”,(录制时我明明输⼊的是“2字符”,录下来咋成了厘⽶为单位呢?)那是否是Excel VBA⾥没有这个函数呢?(我不知道),将=后⾯直接改为数字运⾏通过,最后试下来=20⼤约相当于5号字的“⾸⾏缩进2字符”。(这个20,就是20Points?0.35cm=20 Points?)
(有⼈可能会说这样的办法太笨,有什么好办法请告知。先谢过!)
四、Word vba常⽤语句100句
1、系统参数
(01) Application.ActivePrinter      ‘获取当前打印机
(02) Application.Height          '当前应⽤程序⽂档的⾼度
(03) Application.Width          ‘当前应⽤程序⽂档的宽度
(04) Application.Build          ‘获取Word版本号和编译序号
(05) Application.Caption        ‘当前应⽤程序名
(06) Application.DefaultSaveFormat    '返回空字符串,表⽰Word⽂档
(07) Application.DisplayRecentFiles  '返回是否显⽰最近使⽤的⽂档的状态
(08) Application.Documents.Count      '返回当前打开的⽂档数
(09) Application.FontNames.Count      ‘返回当前可⽤的字体数
(10) Application.Left            ‘返回当前⽂档的⽔平位置
(11) Application.MacroContainer.FullName  '返回当前⽂档名,包括所在路径
Application.MacroContainer.pach          '返回当前⽂档路径
Application.ActiveDocument.Path        ‘获得⽂件的相对路径
(12) Application.NormalTemplate.FullName  '返回⽂档标准模板名称及所在位置
(13) Application.RecentFiles.Count        '返回最近打开的⽂档数⽬
(14) Application.System.CountryRegion    '返回应⽤程序所在的地区代码
(15) Application.System.FreeDiskSpace  ‘返回应⽤程序所在磁盘可⽤空间
(16) Application.System.HorizontalResolution  '返回显⽰器的⽔平分辨率
(17) Application.System.VerticalResolution  '返回显⽰器的垂直分辨率
(18) Application.System.LanguageDesignation  '返回系统所使⽤的语⾔
(19) Application.System.MathCoprocessorInstalled  ‘返回系统是否安装了数学协处理器
(20) Application.System.OperatingSystem  ‘返回当前操作系统名
(21) Application.System.ProcessorType    '返回计算机处理器名
(22) Application.System.Version    ‘返回操作系统的版本号
(23) Application.Templates.Count    '返回应⽤程序所使⽤的模板数
(24) Application.UserName      '返回应⽤程序⽤户名
(25) Application.Version      ‘返回应⽤程序的版本号
2、Documents/Document对象
(26) ActiveDocument.AttachedTemplate.FullName '返回当前⽂档采⽤的模板名及模板所在位置
(27) ActiveDocument.Bookmarks.Count    '返回当前⽂档中的书签数
(28) ActiveDocument.Characters.Count    '返回当前⽂档的字符数
(29) ActiveDocument.CodeName      ‘返回当前⽂档的代码名称
(30) ActiveDocument.Comments.Count ‘  返回当前⽂档中的评论数
(31) ActiveDocument.Endnotes.Count    '返回当前⽂档中的尾注数
(32) ActiveDocument.Fields.Count    '返回当前⽂档中的域数⽬
(33) ActiveDocument.Footnotes.Count ‘返回当前⽂档中的脚注数
(34) ActiveDocument.FullName    '返回当前⽂档的全名及所在位置
(35) ActiveDocument.HasPassword    '当前⽂档是否有密码保护
(36) ActiveDocument.Hyperlinks.Count  '返回当前⽂档中的链接数
(37) ActiveDocument.Indexes.Count    '返回当前⽂档中的索引数
(38) ActiveDocument.ListParagraphs.Count  '返回当前⽂档中项⽬编号或项⽬符号数
(39) ActiveDocument.ListTemplates.Count  '返回当前⽂档中使⽤的列表模板数
(40) ActiveDocument.Paragraphs.Count    '返回当前⽂档中的段落数
(41) ActiveDocument.Password=XXX      '设置打开⽂件使⽤的密码
(42) ActiveDocument.ReadOnly      '获取当前⽂档是否为只读属性
(43) ActiveDocument.Saved      '当前⽂档是否被保存
(44) ActiveDocument.Sections.Count  '当前⽂档中的节数
(45) ActiveDocument.Sentences.Count  ‘当前⽂档中的语句数
vba 字符串函数
(46) ActiveDocument.Shapes.Count    '当前⽂档中的形状数 ,图形?
(47) ActiveDocument.Styles.Count    '当前⽂档中的样式数
(48) ActiveDocument.Tables.Count    ‘当前⽂档中的表格数
(49) ActiveDocument.TablesOfAuthorities.Count ‘返回当前⽂档中的引⽂⽬录数
(50) ActiveDocument.TablesOfAuthoritiesCategories.Count ‘返回当前⽂档中引⽂⽬录类别数
(51) ActiveDocument.TablesOfContents.Count ‘返回当前⽂档中的⽬录数
(52) ActiveDocument.TablesOfFigures.Count  '返回当前⽂档中的图表⽬录数
3、Paragraphs/Paragraph对象
(53) Selection.Paragraphs.Count    '返回所选区域的段落数
(54) Selection.Paragraphs.First    '返回所选区域中的第⼀段
(55) ActiveDocument.Paragraphs(1).LeftIndent    '返回当前⽂档中第⼀段的左缩进值
(56) ActiveDocument.Paragraphs(1).LineSpacing '返回当前⽂档中第⼀段的⾏距
(57) ActiveDocument.Paragraphs(1).OutlineLevel  ‘返回或设置当前⽂档中第⼀段的⼤纲级别
.OutlineLevel = wdOutlineLevel2        ‘2级
.OutlineLevel = wdOutlineLevel3        ‘3级
(58) ActiveDocument.Paragraphs(1).RightIndent ‘返回当前⽂档中第⼀段的右缩进量
(59) ActiveDocument.Paragraphs(1).SpaceBefore '返回当前⽂档中第⼀段的段前间距
(60) ActiveDocument.Paragraphs(1).SpaceAfter ‘返回当前⽂档中第⼀段的段后间距
(61) ActiveDocument.Paragraphs(1).Range.Text  '返回当前⽂档中第⼀段的内容
(62) ActiveDocument.Paragraphs(1).Range.Style.NameLocal  '返回当前⽂档中第⼀段应⽤的样式名
(63) ActiveDocument.Paragraphs(1).Range.Style.Description  '返回当前⽂档中第⼀段所应⽤样式的详细描述
(64) ActiveDocument.Paragraphs(1).Range.Style.Font.Name  '返回当前⽂档中第⼀段所应⽤样式的字体名
(65) ActiveDocument.Paragraphs(1).Range.Style.Font.NameFarEast  '返回或设置⼀种东亚字体名
(66) ActiveDocument.Paragraphs(1).Range.Style.Font.Size '返回或设置当前⽂档中第⼀段所应⽤样式的字体⼤⼩
(67) ActiveDocument.Paragraphs(1).Range.Style.Font.Spacing '返回或设置字符间距
(68) Selection.Words.Count      '所选区域的字数 Sentences对象
(69) Selection.Sentences.Item(1)  '所选区域中的第⼀句的内容 Words对象
(71) ActiveDocument.Words(1).Select  '选择当前⽂档中的第⼀个词
(72) ActiveDocument.Range.Words(1).InsertAfter "我爱你!" '在当前⽂档中的第⼀个词后插⼊“我爱你”
4、Characters对象
(73) Selection.Characters.Count '当前⽂档中所选区域的字符数
(74) ActiveDocument.Paragraphs(1).Range.InsertParagraphAfter'在当前⽂档的第⼀段之后插⼊⼀个新段落
5、Sections/Section对象
(75) ActiveDocument.Sections.First        '当前⽂档的第⼀节
(76) ActiveDocument.Sections.First.PageSetup.BottomMargin '当前⽂档第⼀节所在页的底边距
(77) ActiveDocument.Sections.First.PageSetup.LeftMargin '当前⽂档第⼀节所在页的左边距
(78) ActiveDocument.Sections.First.PageSetup.RightMargin '当前⽂档第⼀节所在页的右边距
(79) ActiveDocument.Sections.First.PageSetup.TopMargin '当前⽂档第⼀节所在页的顶边距
(80) ActiveDocument.Sections.First.PageSetup.PaperSize '返回或设置当前⽂档第⼀节所在页的⼤⼩
(81) ActiveDocument.Sections.First.PageSetup.PageHeight '返回或设置当前⽂档第⼀节所在页的⾼度
(82) ActiveDocument.Sections.First.PageSetup.PageWidth '返回或设置当前⽂档第⼀节所在页的宽度
(83) ActiveDocument.Sections.Add Range:=myRange    '在当前⽂档中添加新节
(84) ActiveDocument.Sections.Item(2)      '当前⽂档中的第⼆节
(85) ActiveDocument.Sections.Last.Range.InsertAfter "⽂档结束!" '在当前⽂档中最后⼀节的结尾添加⽂字“⽂档结束!”
6、Range对象
(86) ActiveDocument.Range(Start:=0, End:=10) '表⽰当前⽂档前10个字符所组成的⼀个Range对象
(87) Set myRange = ActiveDocument.Range(Start:=ActiveDocument.Paragraphs(2).Range.Start, _
End:=ActiveDocument.Paragraphs(4).Range.End) '将当前⽂档第2段⾄第4段设置为⼀个Range对象
(88) ActiveDocument.Paragraphs(1).Range.Copy '复制当前⽂档中的第⼀段
(89) Selection.Copy
Documents.Add.Content.Paste '复制所选内容到新⽂档中
(90) ActiveDocument.Bookmarks("Book1").Copy Name:="Book2" '将Book2书签复制Book1书签标记的位置
(91) Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=4 '将所选内容移⾄⽂档中的第4⾏
(92) Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext '将所选内容移⾄下⼀个表格的第1个单元格
(93) Selection.Range.AutoFormat '为所选内容套⽤格式
(94) ActiveDocument.Content.Font.Name = "Arial" '将当前⽂档的字体设置为斜体
(95) ActiveDocument.Content.Select Selection.Delete '将当前⽂档中的内容删除其它
(96) Documents.Add                '添加⼀个新⽂档
(97) Set myTable = ActiveDocument.Tables.Add(Selection.Range, 2, 2) '在当前⽂档所选区域添加⼀个2⾏2列的表格7、⽂件读写
(98) Open "C:\my.txt" For Input As #1          '打开⼀个⽤于输⼊的⽂件并令其编号为1
(99) Line Input #1, TextLine      '读取被打开⽤于输⼊且编号为1的⽂件
(100) Close #1                  '关闭编号为1的⽂件
五、例⼦。例中的操作全部是录制,然后嫁接的。
例⼦:⽤Excel VBA,将如下Excel表格(考试系统中导出的题库 ),⽣成如下Word⽂档
规程名称题型题⽬内容答案A        答案B        答案C        答案D        正确答案分值有否图形
规程1        选择题题⽬1……        ……        ……        ……        ……        ABCD        2         
规程1        判断题题⽬2……            对        2         
规程2        选择题题⽬3……        ……        ……        ……        ……        A        2         
规程2        判断题题⽬4……            错        2         
规程1
⼀、选择题
1、题⽬1……  (ABCD)
A、……
B、……
C、……
D、……
⼆、判断题
1、题⽬2……  (对)
规程2
⼀、选择题
1、题⽬3……  (A)
A、……
B、……
C、……
D、……
⼆、判断题
1、题⽬4……  (错)
Sub ScWordWd()
'将“题库”中的题⽬,按格式⽣成Word⽂档
Dim I As Integer, J As Integer, Zhs As Integer, Xh As Integer, Dls As String
Dim Lr As String, Bt As String, Bt1 As String, Tx As String, Tx1 As String
Dim Lj As String, Wjm As String
Dim AA
Sheets("题库").Select
Zhs = Sheets("题库").UsedRange.Rows.Count
Bt = Cells(2, 1)        '标题
Tx = Cells(2, 2)        '题型
Xh = 1                  '
Dls = 1                '
'Dim WordApp As Object
'Set WordApp = CreateObject("Word.Application")    '新建Word对象
Dim Wordapp As Word.Application
Set Wordapp = New Word.Application      '新建Word对象
Wordapp.Visible = True                    '可见
'Wordapp.ScreenUpdating = False            '屏幕刷新
Dim WordD As Word.Document      '定义word类
Set WordD = Wordapp.Documents.Add                  '新建⽂档
Wordapp.Selection.WholeStory                  '全选
Wordapp.Selection.Font.Name = "宋体"          '字体
Wordapp.Selection.Font.Size = 10              '字号
For I = 2 To Zhs
Bt1 = Cells(I, 1)
WordD.Paragraphs(Dls).Range.Font.Name = "宋体"            '字体
WordD.Paragraphs(Dls).Range.Font.Size = 10                '字号
If Len(Trim(Bt1)) > 0 Then
Tx1 = Cells(I, 2)
Lr = Cells(I, 3)
If Bt1 <> Bt Then        '标题不同,写标题,居中
If I > 5 Then      '
WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)  '插⼊回车符,增加⼀段
Dls = Dls + 1
WordD.Paragraphs(Dls).Range.Select
'Wordapp.Selection.InsertBreak Type:=wdPageBreak
'WordD.Paragraphs(Dls).Range.InsertBreak Type:=wdPageBreak          '插⼊分页符,两个都没反应?
Wordapp.Selection.InsertBreak Type:=wdSectionBreakNextPage      '插⼊分节符(下⼀页)
WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)              '插⼊回车符,增加⼀段
Dls = Dls + 1
End If
Bt = Bt1
WordD.Paragraphs(Dls).Range.Text = Bt & vbCrLf            '写标题
'WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)        '插⼊回车符,增加⼀段
WordD.Paragraphs(Dls).OutlineLevel = wdOutlineLevel2      '设置⼤纲级别,2级
'WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0)
WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = 0      '取消⾸⾏缩进
'WordD.Paragraphs(Dls).Range.Font.Name = "宋体"            '字体
'WordD.Paragraphs(Dls).Range.Font.Size = 10                '字号
WordD.Paragraphs(Dls).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter          '居中排列
WordD.Paragraphs(Dls).Range.Font.Bold = wdToggle          '加粗
Dls = Dls + 1
Xh = 1
End If
If Tx1 <> Tx Then          '题型不同,写题型
If Tx1 = "选择题" Then
WordD.Paragraphs(Dls).Range.Text = "⼀、选择题"                      '写题型
Else
WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)          '插⼊回车符,增加⼀段
Dls = Dls + 1
WordD.Paragraphs(Dls).Range.Text = "⼆、判断题"                      '写题型
End If
Tx = Tx1
WordD.Paragraphs(Dls).Range.ParagraphFormat.Alignment = wdAlignParagraphJustify    '左对齐
'WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.35)      '⾸⾏缩进2字符,时能⽤时不能⽤,CentimetersToPoints不能被Excel识别?
WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = 20        '⾸⾏缩进,20⼤约相当于5号字的2字符
WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)          '插⼊回车符,增加⼀段
WordD.Paragraphs(Dls).Range.Font.Bold = wdToggle          '加粗
Dls = Dls + 1
Xh = 1
End If
If Tx = "选择题" Then
WordD.Paragraphs(Dls).Range.Text = Xh & "、" & Lr & "  (" & Cells(I, 8) & ")" & vbCrLf      '写题⽬及标准答案
Dls = Dls + 1
WordD.Paragraphs(Dls).Range.Text = "A、" & Cells(I, 4) & vbCrLf        '选项A
Dls = Dls + 1
WordD.Paragraphs(Dls).Range.Text = "B、" & Cells(I, 5) & vbCrLf        '选项B
Dls = Dls + 1
WordD.Paragraphs(Dls).Range.Text = "C、" & Cells(I, 6) & vbCrLf        '选项C
Dls = Dls + 1

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。