【问题标题】:Xlookup on one table from another table in another workbookXlookup 从另一个工作簿中的另一个表中的一个表
【发布时间】:2022-01-20 22:34:56
【问题描述】:

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

【问题讨论】:

    标签: excel vba variables listobject xlookup


    【解决方案1】:

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

     Range("CNSTimeVariance[P Hours]").FormulaR1C1 = "=XLOOKUP(CNSTimeVariance[@Helper],'" & _
           targetFilename & "'!WorseCase[Helper],'" & _
           targetFilename & "'!WorseCase[P Hours],""Not Found"")"
    

    【讨论】:

    • 像魔术一样工作。非常感谢。实际上,我已经坚持了好几天了。另外,当您有时间时,您能否解释一下为什么我们需要这样做?就像为什么 targetFilename 包含在 &
    • @shoaib 您必须将字符串拆分为变量和非变量部分,然后将它们与& 连接起来,这样变量就不会被引号括起来。 "targetFilename" 只是字符串 targetFilename 不是它的值 workbookname.xlsx
    猜你喜欢
    • 2023-03-28
    • 2013-10-23
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多