Consulting

Results 1 to 8 of 8

Thread: VBA to assign & then access a workbook a variable

  1. #1
    VBAX Mentor
    Joined
    Jan 2008
    Posts
    384
    Location

    VBA to assign & then access a workbook a variable

    I'm trying to assign a workbook a variable which is the value of a cell.
    When I try to access that variable, I get an error.
    Why does this not compute as intended.

    The value in Sheets("Sheet1").Range("A5") is = book2.xls saved as text

    Sub wobkGet()
        Dim FTW As Long
        Dim wb2 
        Set wb2 = ThisWorkbook.Sheets("Sheet1").Range("A5")
        FTW = Workbooks(wb2).Workbooks("Sheet1").Cells(3, "E").Value  ' Type Mismatch
    MsgBox FTW
    
    End Sub

  2. #2
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Option Explicit
    
    Sub wobkGet()
        Dim FTW As Long
        Dim wb2 As Workbook
        
        Set wb2 = Workbooks.Open(ThisWorkbook.Sheets("Sheet1").Range("A5").Value)
        FTW = wb2.Sheets("Sheet1").Cells(3, "E").Value
        MsgBox FTW
         
    End Sub

  3. #3
    VBAX Mentor
    Joined
    Jan 2008
    Posts
    384
    Location
    Thanks mana:

    Because I'm selecting a workbook that is already open, ( The most likely senario), it will keep giving me an error.
    I'm just trying to Set wb2 = ThisWorkbook.Sheets("Sheet1").Range("A5").Value

  4. #4
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Option Explicit
    
    Sub wobkGet()
        Dim FTW As Long
        Dim wb2 As String
        
        wb2 = ThisWorkbook.Sheets("Sheet1").Range("A5").Value
        FTW = Workbooks(wb2).Worksheets("Sheet1").Cells(3, "E").Value
        MsgBox FTW
         
    End Sub

  5. #5
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,645
    Sub M_snb() 
        msgbox Workbooks(ThisWorkbook.Sheets("Sheet1").cells(5,1)).sheets("Sheet1").Cells(3, 5).Value 
    End Sub

  6. #6
    VBAX Mentor
    Joined
    Jan 2008
    Posts
    384
    Location
    Thanks mana:

    That code works as expected. Appreciate it.

  7. #7
    VBAX Mentor
    Joined
    Jan 2008
    Posts
    384
    Location
    Hi snb:

    Thanks.
    Not sure why but that code gave me an error.
    I was looking for a solution that let me use Workbooks(wb2). in the format like I was trying.

  8. #8
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,645
    Avoid variables that do not vary:

    Sub M_snb() 
        msgbox Workbooks(ThisWorkbook.Sheets("Sheet1").cells(5,1).value).sheets("Sheet1").Cells(3, 5).Value 
    End Sub
    And prefer With ... End With to object variables.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •