title: Reading an already open workbook in visual basic (on visual studio)
body: <p>I work on a VB project and use Visual Studio 2015 after a switch from VBA to VB. I need to read some information from an Excel Workbook. Since this file might have already been opened, I do not want to open it again, so structure of my script is as follows:</p>
  
  <p>(Function) Check that the file is open ( "works perfectly")</p>
  
  <p>If it is open ("Problematic")</p>
  
  <ul>
  <li>Access the file   </li>
  <li>Activate a specific sheet</li>
  <li>Read information</li>
  </ul>
  
  <p>Else (the file is not open)----("works perfectly")</p>
  
  <ul>
  <li>Open the file</li>
  <li>Activate a specific sheet</li>
  <li>Read information</li>
  </ul>
  
  <p>End if</p>
  
  <p>In this structure, I have already spent three days for the first part but any script that I found on the Internet did not work in my project. Many people claim that given script works, however, I got an error on line 12 because oWB equals "Nothing" on line 11. </p>
  
  <p>I could not figure out what the problem is. Simply, I need an assignment like that (this works only in VBA):</p>
  
  <pre><code>Set oWB=Workbooks("sample.xlsx") 
  </code></pre>
  
  <p>And, my whole script is following:</p>
  
  <pre><code>Imports Microsoft.Office.Interop
  
  Module Module1
  
  Sub ReadInformation() 'Line 1
   Dim oXL As Excel.Application
   Dim oWB As Excel.Workbook
   Dim oWS As Excel.Worksheet
   Dim filepath2 As String 'Line 5
  
   filepath2 = "C:\Users\IEN 271\Desktop\sample.xlsx" 
  
   If FileInUse(filepath2) Then
    oXL = New Excel.Application
    oXL = GetObject(, "Excel.Application")
    oXL.Visible = True
    oWB = oXL.ActiveWorkbook 'Line 11
    oWS = oWB.Worksheets("sampleSheet")
    oWS.Activate()
   Else
    oXL = New Excel.Application
    oXL.Visible = True
    oWB = oXL.Workbooks.Open("C:\Users\IEN 271\Desktop\sample.xlsx", [ReadOnly]:=False)    
    oWS = oWB.Worksheets("sampleSheet")
    oWS.Activate()
   End If
  
   'Script for reading process (fine)
  End Sub
  
  End Module
  </code></pre>
  
  <p>Any help would be a lot appreciated.</p>
  
  <p>Thanks!</p>