打开最新文件并将数据复制到不同的工作簿

时间:2014-08-12 16:17:10

标签: excel excel-vba copy vba

我对VBA完全陌生。我正在尝试编写宏从文件夹中打开最新文件以及从特定工作表复制和过去数据。我需要从VBA打开的文件(文件夹中的最新文件)中复制数据,并将数据从一个工作表复制到我当前的文件(到期日期表)。

我不知道如何将打开文件声明为我要复制数据的工作簿。有什么建议吗?

Private Sub CommandButton1_Click()

'Declare the variables
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date


Set Y = Workbooks("TEST")


MyPath = "C:\Users\e9\Desktop\Automatyczne sprawdzanie expiry date\New folder\"


If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"


MyFile = Dir(MyPath & "*.xls", vbNormal)


If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If


Do While Len(MyFile) > 0


    LMD = FileDateTime(MyPath & MyFile)

    If LMD > LatestDate Then
        LatestFile = MyFile
        LatestDate = LMD
    End If

    MyFile = Dir


Loop

Workbooks.Open MyPath & LatestFile

End Sub

2 个答案:

答案 0 :(得分:0)

打开最新文件后,

      Sheets("x").Activate
      ActiveSheet.Range("x:y").select
      selection.copy
      workbooks("x").activate
      sheets("X").activate
      activesheet.range("x").select
      selection.paste

用所需的名称/范围替换xs和ys。 之后继续你的循环

答案 1 :(得分:0)

以下是从各种参考文献中获取的代码示例..

Find Last modified file 您必须为FileSystemObject添加引用.. FileSystemObject how to add reference

通过向目标文件(Book2.xlsm)上的工作表添加ActiveX按钮进行测试。改变路径,也&#34; Book2.xlsm&#34;你的路径和文件名。

    Dim sFldr As String
Dim fso As Scripting.FileSystemObject
Dim fsoFile As Scripting.File
Dim fsoFldr As Scripting.Folder
Dim dtNew As Date, sNew As String
Dim sFileName As String

Set fso = New Scripting.FileSystemObject

sFldr = "C:\Temp\stackoverflow\excel\"

Set fsoFldr = fso.GetFolder(sFldr)

For Each fsoFile In fsoFldr.Files
    If fsoFile.DateLastModified > dtNew Then
        sNew = fsoFile.Path
        sFileName = fsoFile.Name
        dtNew = fsoFile.DateLastModified
    End If
Next fsoFile

Workbooks.Open Filename:=sNew
Sheets("Sheet1").Copy Before:=Workbooks("Book2.xlsm").Sheets(1)
Windows(sFileName).Activate
ActiveWindow.Close