如何在代码中使用最新文件功能进行vlookup

时间:2019-07-09 17:23:10

标签: excel vba vlookup

您好,我使用的是调用文件夹中最新文件的函数。我需要自动执行该文件的vlookup。我在正确调出文件时遇到问题

我已经尝试通过它的路径来调用它,但是我相信我没有正确地调用它。

Sub oversub()

    'Newest file function

        Dim MyPath As String
        Dim MyFile As String
        Dim LatestFile As String
        Dim LatestDate As Date
        Dim LMD As Date

        MyPath = "C:\Users\TAmon1\Desktop\OverSubscription Dash"
        If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
        MyFile = Dir(MyPath & "*.csv", 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
    Dim wb As Workbook
    'wbstring = MyPath & LatestFile
    Windows("Planning_tool.xlsm").Activate


'Vlookupfunction
    Range("N2").Select
    ActiveCell.FormulaR1C1=VLOOKUP(C[-13],'Router_level_crosstab.csv'!C1:C11,11,FALSE)"

当前,我正在调用可以正常工作的直接文件,但是当我有一个新文件时,我将需要手动更改文件名。我需要将最新文件合并到Vlookup中。

1 个答案:

答案 0 :(得分:0)

Dim wbCSV As Workbook, wbPlanning as Workbook
Set wbPlanning = Workbooks("Planning_tool.xlsm")
'...
'...
Set wbCSV = Workbooks.Open(MyPath & LatestFile) '<< save the reference to the opened file
'...
'...
'don't rely on activeworkbook, activesheet, etc
wbPlanning.Sheets(1).Range("N2").FormulaR1C1 = _
         "=VLOOKUP(C[-13],'" & wbCSV.Name & "'!C1:C11,11,FALSE)"