使用excel VBA宏打开与单元格内容同名的word文档
2017-02-22 本文已影响0人
雷澈
想要做一个在excel中单击某个单元格,然后根据该单元格的内容,打开一个对应word文档的功能。并没有怎么用过excel,之前大概知道这东东有很强大的宏功能。OK,那就来试试。
Excel2007中打开“开发工具”选项卡
- 首先点击左上角 fig1
- 然后点击弹窗右下角的“Excel选项”按钮 fig2
- 然后勾选“在功能区显示‘开发工具’选项卡”这个按钮 fig3
- OK,Excel2007窗口应该已经有“开发工具”这个选项卡了,可以进行下一步操作
Excel2007执行macro
- 首先切换到“开发工具”选项卡,确保“设计模式”(design mode)按钮已按下,点击“插入”,选择“ActiveX控件”中的“命令按钮”(command button) fig4
- 紧接上一步,在文本中合适位置拖一个按钮出来 fig5
- 在“设计模式”按钮按下的情况下,在拖出来的这个按钮上右键,选择“查看代码” fig6
- 点击“查看代码”后,会出现一个新弹窗,在这个弹窗中如图所示位置,加入测试代码(
Range("A1").Value="Hello"
),然后关闭代码窗口 fig7 - 点击一下“设计模式”按钮,退出设计模式;然后点击刚才拖出来的那个按钮一次,会发现A1单元格的值变成了“Hello”,测试成功 fig8
- 实际上,只要点击“开发工具”栏的“Visual Basic”按钮,就可以直接打开VB代码窗口进行编辑 fig9
VBA介绍
VBA(Visual Baisc for Applications) is the programming language of Excel and other Office programs.
VBA调试
to be continued
用excel宏打开对应word文档
首先创建测试文档,比如,在H:\test\下创建test-doc目录,新建3个docx文件 doc1 在H:\test\下创建test-excel目录,新建一个xlsx文件 doc2按照前面的例子,在excel文档中添加按钮,按钮的VBA代码填下面这段(搜索docx的目录要按需要修改)
Private Sub CommandButton1_Click()
Dim dirVal As String
Dim fileVal As String
Dim targetVal As String
Dim objWord
Dim objDoc
Dim found
Set objWord = CreateObject("Word.Application")
targetVal = ActiveCell.Value ' 当前选中单元格的值
If targetVal = "" Then ' 当前选中单元格为空
MsgBox "目标值为空!"
Exit Sub
End If
Application.ScreenUpdating = False
dirVal = "H:\test\test-doc\" ' 搜索word文档的目录,根据需要修改
fileVal = Dir(dirVal & "*.do??")
found = 0
Do While fileVal <> ""
If InStr(fileVal, targetVal) <> 0 Then
Set objDoc = objWord.Documents.Open(dirVal & fileVal) '&注意加空格
objWord.Visible = True
found = 1
Exit Do
End If
fileVal = Dir()
Loop
If found = 0 Then ' 没有找到合适的word文档
MsgBox "没有docx文件叫这个名字"
End If
Application.ScreenUpdating = True
End Sub
OK,done。在excel文档中填这样几个值用来测试
doc3
如果选中个空白单元格,点击按钮,会弹出
doc4
如果选中内容为“test”的单元格,点击按钮,会弹出
doc5
如果选中内容为“HarryPotter.docx”的单元格,点击按钮,那对应的docx文档就自动打开了
doc6
Enjoy.
参考链接
- http://www.excel-easy.com/vba/create-a-macro.html
- http://jingyan.baidu.com/article/39810a23c863a4b636fda6d9.html
- http://www.excel-easy.com/vba/examples/files-in-a-directory.html
- http://www.excel-easy.com/vba.html