我是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 回答
打开最新文件后,
用所需的名称/范围替换xs和ys . 然后继续你的循环
以下是从各种参考文献中获取的代码示例
Find Last modified file您必须为FileSystemObject添加引用.. FileSystemObject how to add reference
通过向目标文件(Book2.xlsm)上的工作表添加ActiveX按钮进行测试 . 将路径和“Book2.xlsm”更改为您的路径和文件名 .