0

我有两个表 -CNSTimeVariance一个工作簿WorseCase中的表和一个名为的文件中的表Financial Model v12.xlsx,我在目录中找到并打开它作为最近的文件。与此文件关联的变量是targetFilename. 问题是这个文件名会不时改变,我想让它动态化。如何将Financial Model v12.xlsx以下代码最后一行中给出的 xlookup 公式替换为targetFilename

SUB Xlookup()

    Sheets("CNS Time Total").Select

    Dim CNSTimeVariance As ListObject
    Set CNSTimeVariance = ActiveSheet.ListObjects("CNSTimeVariance")

    Dim DWB As Workbook
    Set DWB = ActiveWorkbook

    Dim FileSys As FileSystemObject
    Dim objFile As File
    Dim myFolder
    Dim targetFilename As String
    Dim dteFile As Date

    Const myDir As String = "C:\My Desktop Folders\Edge\7. Financial Models\"
    
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)
        
    dteFile = DateSerial(1900, 1, 1)
    For Each objFile In myFolder.Files
        If objFile.DateLastModified > dteFile Then
            dteFile = objFile.DateLastModified
            targetFilename = objFile.Name
        End If
    Next objFile

    MsgBox targetFilename

    Workbooks.Open (myDir & targetFilename)
            
    'Set FileSys = Nothing
    'Set myFolder = Nothing

    DWB.Activate

    Range("CNSTimeVariance[P Hours]").FormulaR1C1 = _
       "=XLOOKUP(CNSTimeVariance[@Helper],'Financial Model v12.xlsx'!WorseCase[Helper],'Financial Model v12.xlsx'!WorseCase[P Hours],""Not Found"")"

End Sub
4

1 回答 1

0

将变量连接到公式字符串中

 Range("CNSTimeVariance[P Hours]").FormulaR1C1 = "=XLOOKUP(CNSTimeVariance[@Helper],'" & _
       targetFilename & "'!WorseCase[Helper],'" & _
       targetFilename & "'!WorseCase[P Hours],""Not Found"")"
于 2021-12-18T13:36:57.723 回答