如何在Excel VBA 中读写word文档 步骤

如何在Excel VBA 中读写word文档 步骤,第1张

1. 库的咐或配置

在默认情况下,新创建的excel vba中不支持定义word对象。

所以需要先引入word库, *** 作步骤如下:

1.1 打开excel vba 界面

1.2 选中其中的一个Module

1.3 选择菜单, Tools -->References

在打开的对话框中选择类似 "Microsoft Word 14.0 Object Library".

1.4 点击OK保存配置。

2. 打开文档清庆

Set wordApplication = CreateObject("Word.Application")

wordApplication.Visible = False

Dim hasOpenDoc As Boolean

hasOpenDoc = IsOpen(filePath) ' is a self-defined function to check file is opend

If hasOpenDoc = True then

Set wordDoc = GetObject(filePath)

End if

If hasOpenDoc = False Then

Set wordDoc = wordApplication.Documents.Open(filePath)

End if

wordDoc.Active

With wordApplication

Dim aParagraph As Word.Paragraph

For Each aParagraph In wordDoc.Paragraphs

' do some thing to every paragraph.

Next aParagraph

End with

wordDoc.Close

Set wordDoc = nothing

' 如下这段代码引用某位牛人的,非常感谢他。由于路径丢失答简握,不能给出链接, 抱歉

' 如下的找寻方式,能够正确的找出文件是否被打开

Function IsOpen(fileName As String) As Boolean

IsOpen = False

Dim findFile As Integer

findFile = FreeFile()

On Error GoTo ErrOpen

Open fileName For Binary Lock Read Write As findFile

Close findFile

Exit Function

ErrOpen:

If Err.Number <>70 Then

Msg = "Error # " &Str(Err.Number) &"was generated by " &Err.Source &Chr(13) &Err.Description

MsgBox Msg, "Error", Err.HelpFile, Err.HelpContext

Else

IsOpen = True

End If

End Function

举例如下

3.2 VBA中与文件读取的相关方法

首先我们来介绍一下使用到的几个方法:

Open方法。氏虚该方法用于打开文件汪核好,打开后可以得到一个特殊的编号,之后再读取文件的数据都需要该编号。

FreeFile函数。

Get方法。使用Open方法打开文件后,该方法可以按字节读取数据。

Seek方法。使用Open方法打开文件后,该方法可以用于定位指定的文件位置(即地址)。

Sub OpenFileTesting()

Dim FS As Integer 'File No.

Dim Val1As Integer

Dim Val2(1) As Byte

Dim Val3(2) As Integer

FS = FreeFile '获困铅取一个文件流

'打开文件

Open ThisWorkbook.Path &"\test.xls" For Binary Access Read As FS

'顺序读取数据至3个变量

Get FS, , Val1

Get FS, , Val2

Get FS, , Val3

Close FS'关闭文件流

Stop

End Sub

建议用FileSystemObject *** 作:

示例

Sub ReadTextFile() 

Dim fs As Object 

Dim objFile As Object 

Dim strContent As String 

Dim strFileName As String 

   

 strFileName = "C:\aaa.txt"亏返  '此处可以用其他变量代替

Set fs = 陵空芦CreateObject("Scripting.FileSystemObject") 

Set objFile = fs.OpenTextFile(strFileName) 

    

Do While Not objFile.AtEndOfStream 

   strContent = strContent & objFile.ReadLine & vbCrLf  

Loop 

    

objFile.Close 

Set objFile = Nothing 

ActiveWorkbook.Sheets(3).Select 

Range("A1").Select     

Selection.Formula = strContent

End

另外,你用了Application.FileDialog(msoFileDialogOpen)打开文件,选择后实际上是没有打开文件的动作的,

需要尺带用代码打开,文件名就是上面网友回答的“FileName = fd.SelectedItems(1) '记录文件路径(指定文本文件名)”

然后使用你常用的Workbooks.OpenText命令打开吧!

不然肯定是“打开以后什么都没有,跟没打开似的”了!


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/12126643.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-21
下一篇2023-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存