打开文件夹中最新文件的代码。然后宏将信息提取到我的工作簿中

时间:2019-09-29 19:32:08

标签: excel vba file

我有打开指定文件夹中最新工作簿文件的代码。问题是我设置为从该工作簿文件中提取信息的宏不能每周工作,因为我需要从中获取信息的工作簿文件是每周的存档文件。该宏引用了名为2019-09-16的工作簿文件,但下周该工作簿文件将为2019-09-20,无论如何该宏将无法正常工作?

如果我可以获得一些代码来复制工作簿。然后,将副本以通用名称(例如存档)保存在另一个文件夹中。那将允许我运行一个宏以从该工作簿中获取信息。

我尝试键入打开最新文件所需要的代码,以帮助将某些内容与宏链接在一起,但是键入时出现了太多错误。任何帮助将不胜感激。

Sub OpenLatestFile()

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

MyPath = "\\C\s\CAF7\Stats\Team 1\Archive\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)

Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)


LMD = FileDateTime(MyPath & MyFile)

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

Loop
Workbooks.Open MyPath & LatestFile

Windows("Teams.xlsm").Activate
Range("F11").Select
ActiveCell.FormulaR1C1 = "='[Workbooks.Open MyPath & LatestFile]Managers Sheet'!R33C13"
Range("E12").Select
ActiveCell.FormulaR1C1 = "='[Workbooks.Open MyPath & LatestFile]Managers Sheet'!R24C13"
Range("D9").Select
ActiveCell.FormulaR1C1 = "='[Workbooks.Open MyPath & LatestFile]Managers Sheet'!R38C13"
Range("F13").Select
ActiveCell.FormulaR1C1 = "='T1'!R[7]C"
Range("F14").Select
ActiveCell.FormulaR1C1 = "='T1'!R[20]C"
Range("F15").Select
ActiveCell.FormulaR1C1 = "='T1'!R[33]C"
Range("F16").Select
ActiveCell.FormulaR1C1 = "='t1'!R[19]C[2]"
Range("F17").Select
ActiveCell.FormulaR1C1 = "='t1'!R[18]C[8]"
Range("E18:F27").Select
End Sub

这是我试图解决的问题,工作簿可以正常打开,但是当尝试运行宏时,它会尝试从引用中查找工作簿,并且无法找到?

1 个答案:

答案 0 :(得分:0)

如果文件中只有一张工作表(包含当前更新的信息),则只需按其索引引用工作表

TheLatestFile.Worksheets(1)

如果有多个工作表,并且您可以确定它在工作簿选项卡顺序中的位置,则可以改用该已知索引位置。

TheLatestFile.Worksheets(KnownIndex)

如果有多个工作表,并且您不知道其在选项卡顺序中的位置,则可以确保从代码名中获取正确的工作表(如果可以确保代码名一致)。这种方法要求代号每周不更改(更新的文件到更新的文件),并且您将需要信任对VBA项目模型的访问。