After, if you want to auto fit all columns,
You need to add this part:
Code:
'Auto column fit
Dim c As Long
Dim z As Long
Dim cell_wid As Single
Dim col_wid As Single
For c = 0 To MSFlexGrid1.Cols - 1
col_wid = 0
For z = 0 To MSFlexGrid1.Rows - 1
cell_wid = TextWidth(MSFlexGrid1.TextMatrix(z, c))
If col_wid < cell_wid Then col_wid = cell_wid
Next z
MSFlexGrid1.ColWidth(c) = col_wid + 120
Next c
FULL CODE:
Code:
Option Explicit
Private Sub FetchNoRowCol(ws As Excel.Worksheet, ByRef NoOfRows As Long, _
ByRef NoOfColumns As Long)
' Error-handling is here in case there is not any
' data in the worksheet.
On Error Resume Next
NoOfRows = ws.Cells.Find(What:="*", SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
NoOfColumns = ws.Cells.Find(What:="*", SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
End Sub
Private Sub Command1_Click()
Dim xlObject As Excel.Application
Dim xlWB As Excel.Workbook
Dim NoOfRows As Long
Dim NoOfColumns As Long
On Error GoTo MyErrHandler
With CommonDialog1
.CancelError = True
.Filter = "Microsoft Excel files (xlam, xlsx, xltm, xlt, xlsm, xltx, xls, txt, csv)"
.InitDir = "C:\Documents and Settings\all users\Desktop"
.ShowOpen
If Not .FileName = "" Then
Set xlObject = New Excel.Application
Set xlWB = xlObject.Workbooks.Open(.FileName)
Clipboard.Clear
xlObject.Cells.Copy ' Copy all cells in active worksheet.
FetchNoRowCol xlObject.ActiveWorkbook.ActiveSheet, NoOfRows, NoOfColumns
With MSFlexGrid1
.Redraw = False 'Dont draw until the end, so we avoid that flash
.Rows = NoOfRows
.Cols = NoOfColumns
.Row = 0 'Paste from first cell
.Col = 0
.RowSel = .Rows - 1 'Select maximum allowed (your selection shouldnt be greater than this)
.ColSel = .Cols - 1
.Clip = Replace(Clipboard.GetText, vbNewLine, vbCr) 'Replace carriage return with the correct one
.Col = 1 'Just to remove that blue selection from Flexgrid
.Redraw = True 'Now draw
End With
xlObject.DisplayAlerts = False 'To avoid "Save woorkbook" messagebox
xlWB.Close
xlObject.Application.Quit
Set xlWB = Nothing
Set xlObject = Nothing
End If
End With
'Auto column fit
Dim c As Long
Dim z As Long
Dim cell_wid As Single
Dim col_wid As Single
For c = 0 To MSFlexGrid1.Cols - 1
col_wid = 0
For z = 0 To MSFlexGrid1.Rows - 1
cell_wid = TextWidth(MSFlexGrid1.TextMatrix(z, c))
If col_wid < cell_wid Then col_wid = cell_wid
Next z
MSFlexGrid1.ColWidth(c) = col_wid + 120
Next c
Exit Sub
MyErrHandler:
Err.Clear
End Sub