Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. Imports System.Runtime.InteropServices
  2.  
  3. Public Class Form1
  4.  
  5.  
  6. <DllImport("User32")> _
  7. Private Shared Function SetParent(ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
  8. End Function
  9.  
  10. <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
  11. Private Shared Function FindWindow( _
  12. ByVal lpClassName As String, _
  13. ByVal lpWindowName As String) As IntPtr
  14. End Function
  15.  
  16.  
  17. Private Const mconXLWindowClass As String = "XLMAIN"
  18.  
  19.  
  20. Private mXL As Object
  21.  
  22.  
  23. Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
  24.  
  25. Dim OFD As OpenFileDialog
  26.  
  27.  
  28. OFD = New OpenFileDialog()
  29. With OFD
  30. .CheckFileExists = True
  31. .CheckPathExists = True
  32. .Filter = "Test files (*.txt)|*.txt|Excel spreadsheets (*.xls, *.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*"
  33. .FilterIndex = 2
  34. .InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  35. .RestoreDirectory = True
  36. .Title = "Select Data File"
  37. If .ShowDialog = DialogResult.OK Then
  38. txtPath.Text = .FileName
  39. OpenExcel(tpDisplay.Handle, True)
  40. 'OpenExcel(True)
  41. End If
  42. End With
  43.  
  44. End Sub
  45.  
  46. Private Sub OpenExcel(ByVal bShow As Boolean)
  47.  
  48. OpenExcel(IntPtr.Zero, bShow)
  49.  
  50. End Sub
  51.  
  52. Private Sub OpenExcel(ByVal hwnd As IntPtr, ByVal bShow As Boolean)
  53.  
  54. Dim hwndExcel As IntPtr
  55.  
  56.  
  57. Try
  58.  
  59.  
  60. mXL = CreateObject("Excel.Application")
  61.  
  62. If hwnd <> IntPtr.Zero Then
  63.  
  64. hwndExcel = FindWindow(mconXLWindowClass, mXL.Caption)
  65. SetParent(hwndExcel, hwnd)
  66.  
  67. End If
  68.  
  69. mXL.Visible = bShow
  70. OpenFile()
  71.  
  72.  
  73. Catch ex As Exception
  74.  
  75. MsgBox(ex.Message)
  76.  
  77. End Try
  78.  
  79. End Sub
  80.  
  81.  
  82. Private Sub OpenFile()
  83.  
  84. Dim objWorkbooks As Object
  85.  
  86.  
  87. objWorkbooks = mXL.Workbooks
  88. objWorkbooks.Open(txtPath.Text)
  89.  
  90. While (System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkbooks) > 0)
  91. End While
  92. objWorkbooks = Nothing
  93.  
  94. End Sub
  95.  
  96. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement