VBA自动保存文件

时间:2015-04-22 07:40:44

标签: vba loops ms-word save word-vba

我正在尝试自动保存指定文件夹中的文件。 比如ResultTest1ResultTest2ResultTest3等等。

Dim savedName As String
Dim arNames() As String
Dim myCount As Integer

savedName = Dir$("D:\Users\tmp4jj\Desktop\ComparisonTool\ResultTest*.docx")
Do Until savedName = ""
    myCount = myCount + 1
    ReDim Preserve arNames(1 To myCount)
    arNames(myCount) = savedName
    savedName = Dir$
Loop

我一直在试用这段代码,但我不确定它是否真的有效。此外,我尝试录制一个宏,我事先更改了保存文件目的地的选项。这些代码弹出,不确定它是否有用。

ActiveDocument.SaveAs2 FileName:="ResultTest.docx", FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False, CompatibilityMode:=14

1 个答案:

答案 0 :(得分:0)

如果您想使用具有某些功能的文件,我建议您使用FileSystemObject com object

在项目中有很多使用它的例子:

  1. Get content of the directory using wildcast with FileSystemObject
  2. How can I use the FileSystemObject to “Copy and rename”
  3. 您还可以在循环中使用like运算符来查找文件-in(1)sample-;像这样:

    IF (f1.name like "ResultTest*.docx") THEN
        ' Write your code here
    END IF
    

    On Error Resume Next
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' Getting file name by default input window
    Flname = InputBox("Enter File Name :", "Creating New File...")
    If Flname <> "" Then
    
        ' adding a new workbook
        Set NewWkbk = Workbooks.Add
    
        ' Copy data from a sheet (e.g 5) from current workbook to a sheet (e.g 1) in that new one
        ThisWorkbook.Sheets(5).Copy Before:=NewWkbk.Sheets(1)
    
        ' Create excel file by saving the new workbook as file name
        NewWkbk.SaveAs ThisWorkbook.Path & "\" & Flname
    
        If Err.Number = 1004 Then
            NewWkbk.Close
            MsgBox "File Name Not Valid."
            Exit Sub
        End If
    End If