简体   繁体   中英

VBA to open Excel file based on cell value WITHIN that file

I've been looking all over the web for an answer to this question. I see many blogs and postings regarding opening an excel file based on a cell value NOT within that file.

My question: Is it possible to open a file based on a cell value within the file I am trying to open? Another way to word it: Can VBA search for a cell value within a file, that is not open, and then open that file if it finds that cell value?

Further Explanation:

I save reports from a system into a folder and these files being saved have a common name (Report, Report (1), Report (2), Report (3).....). However, the data within the reports are different. They all have a common cell (Cell A7) that designates what the report is for. I want to use VBA code to open one of these files based on its value in cell A7. Is this even possible?

Thank you in advanced for any direction here.

If you know the sheet name you can use ExecuteExcel4Macro . If the sheet name is not known then you can use ADO to get that first (easier here as there's only one sheet)

Example:

Sub Tester()
    
    Const fldr As String = "C:\Excel\Temp\"
    Dim f, v
    
    f = Dir(fldr & "*.xlsx")
    'loop over all files in folder
    Do While Len(f) > 0
        'passing empty string for sheetname, since we don't know it...
        v = ReadCell(fldr, f, "", Range("A7").Address(True, True, xlR1C1))
        Debug.Print f, v
        f = Dir
    Loop

End Sub

'Read a cell value given a workbook path, name, optional sheetname,
'  and cell address (R1C1 format)
Function ReadCell(fPath, wbName, wsName, addr)
    Const adSchemaTables = 20
    Dim cn, conStr, rs
    
    If Len(wsName) = 0 Then
        'sheet name is not known, so find the first name using ADO
        conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fPath & wbName & "';" & _
                 "Extended Properties=""Excel 12.0;HDR=NO;IMEX=1;"";"
        Set cn = CreateObject("ADODB.connection")
        cn.Open conStr
        Set rs = cn.openschema(adSchemaTables)
        wsName = Replace(rs("TABLE_NAME").Value, "$", "")
        rs.Close
        cn.Close
    End If
    
    ReadCell = ExecuteExcel4Macro("'" & fPath & "[" & wbName & "]" & _
                                  wsName & "'!" & addr)
    
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM