遍历目录中的所有Word文件

use*_*061 6 vba ms-word

我有以下代码:

Sub WordtoTxtwLB()
'
' WordtoTxtwLB Macro
'
'
Dim fileName As String
myFileName = ActiveDocument.Name

ActiveDocument.SaveAs2 fileName:= _
"\\FILE\" & myFileName & ".txt", FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, Encoding:=1252, InsertLineBreaks:=True, AllowSubstitutions:=False, _
LineEnding:=wdCRLF, CompatibilityMode:=0


End Sub
Run Code Online (Sandbox Code Playgroud)

我想通过目录中的所有单词(.doc)文件循环此子.我有以下代码:

Sub LoopDirectory()

vDirectory = "C:\programs2\test"

vFile = Dir(vDirectory & "\" & "*.*")

Do While vFile <> ""

Documents.Open fileName:=vDirectory & "\" & vFile

ActiveDocument.WordtoTxtwLB

vFile = Dir
Loop

End Sub
Run Code Online (Sandbox Code Playgroud)

但它没有用.如何通过更改当前代码或使用新代码来实现此功能?

Sid*_*out 11

您实际上并不需要WordtoTxtwLB宏.您可以将两个代码组合在一起.看这个例子

(UNTESTED)

Sub LoopDirectory()
    Dim vDirectory As String
    Dim oDoc As Document

    vDirectory = "C:\programs2\test\"

    vFile = Dir(vDirectory & "*.*")

    Do While vFile <> ""
        Set oDoc = Documents.Open(fileName:=vDirectory & vFile)

        ActiveDocument.SaveAs2 fileName:="\\FILE\" & oDoc.Name & ".txt", _
                               FileFormat:=wdFormatText, _
                               LockComments:=False, _
                               Password:="", _
                               AddToRecentFiles:=True, _
                               WritePassword:="", _
                               ReadOnlyRecommended:=False, _
                               EmbedTrueTypeFonts:=False, _
                               SaveNativePictureFormat:=False, _
                               SaveFormsData:=False, _
                               SaveAsAOCELetter:=False, _
                               Encoding:=1252, _
                               InsertLineBreaks:=True, _
                               AllowSubstitutions:=False, _
                               LineEnding:=wdCRLF, _
                               CompatibilityMode:=0

        oDoc.Close SaveChanges:=False
        vFile = Dir
    Loop
End Sub
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你确定要使用*.*通配符吗?如果文件夹中有Autocad文件怎么办?同时ActiveDocument.Name会给你的扩展名的文件名.