我有一些循环遍历行的代码,找到要复制的所需区域,将其复制到Word,然后将其另存为“txt”文件。它工作正常,但在全尺寸样本上运行时创建80多个文件相当慢。我相信这是因为下面的代码是每次运行时打开和关闭Word而不是让它打开但我不确定如何让它保持打开并创建新文档。有没有办法做到这一点或其他方式加快代码?
Set wrdapp = CreateObject("Word.Application")
wrdapp.Visible = False
Set wrddoc = wrdapp.Documents.Add
Rows(endingrow + 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(endingrow + 1, "A").Value = "%"
Rows(startingrow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(startingrow, "A").Value = "%"
endingrow = endingrow + 2
Range(Cells(startingrow, "A"), Cells(endingrow, "A")).Copy
With wrdapp
.Selection.PasteAndFormat (wdFormatPlainText)
.Visible = True
.Selection.WholeStory
End With
With wrdapp.Selection.ParagraphFormat
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineUnitBefore = 0
End With
wrdapp.ChangeFileOpenDirectory GetFolder
wrdapp.ActiveDocument.SaveAs2 filename:=filename, FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False
wrdapp.Quit
答案 0 :(得分:0)
如果你想在MS Word中继续这样做并保存为文本文件,有几点需要注意......
1 - 您创建了wrdDoc
但似乎没有使用它。
2 - 您可以替换它:
With wrdapp
.Selection.PasteAndFormat (wdFormatPlainText)
.Visible = True
.Selection.WholeStory
End With
用这个:
wrdDoc.Range.Paste
3 - 如果你保存为文本文件,你真的不需要这个......
With wrdapp.Selection.ParagraphFormat
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineUnitBefore = 0
End With
4 - 最后,要关闭文档并打开应用程序,您可以执行以下操作:wrdDoc.Close
(即使用您创建的文档)而不是wrdapp.Quit
< em>(关闭Word应用程序)
除此之外,是的,您可以按照@ScottHoltzman的建议直接写入文本文件