How to manipulate an excel workbook with Excel.Workbook - vb.net

So, I can't find any methods with file opening in Excel.Workbook or Excel.Application, and I am wondering why.
I have path to an Excel file, and I would like to manipulate it. I understand I have to use Excel.Application, Excel.Workbook, and Excel.Worksheet. The file to the Excel file is ExcelFilePath, what should I do to make it possible?

You first need to add the reference to Microsoft.Office.Interop.Excel to your project in order to use the Excel API, then fill the variables:
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWS As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(sFilePath)
xlWS = CType(xlWorkBook.Worksheets(sheetNameOrIndex), Excel.Worksheet)
And then you only need to use the methods they have. For example:
Dim sVar as String = xlWS.Range("C5").Value.ToString()

Try this: from my project
Dim xapp As New Microsoft.Office.Interop.Excel.Application
Dim wb As Workbook = xapp.Workbooks.Add
Dim ws As Worksheet = wb.Worksheets(1)
ws.Activate()
'Fill header of the sheet----------------------------------
For i As Integer = 1 To dgvcustomer.Columns.Count
ws.Cells(1, i) = dgvcustomer.Columns(i - 1).HeaderText
Next
'End header------------------------------------------------
Dim Dgrow, Dgcell, Dgcol As Integer
Dgrow = 1
Dgcell = 1
'Fill Sheet ------------------------------------------------------------------------------------------------
While (Dgrow <= dgvcustomer.Rows.Count)
Dgcol = 1
While (Dgcol <= ws.UsedRange.Columns().Count)
ws.Cells(Dgrow + 1, Dgcol).value = dgvcustomer.Rows(Dgrow - 1).Cells(ws.Cells(1, Dgcol).value).Value
Dgcol += 1
End While
Dgrow += 1
End While
'End fill sheet---------------------------------------------------------------------------------------------
wb.SaveAs(dlgSaveFile.FileName)
wb.Close()
xapp.Quit()

Related

Issues Preserving Format from Word to Excel

I'm struggling trying to export a Word table to an Excel sheet, while preserving the number formatting. My code works as shown below, but the part I commented out is how I'm currently trying to do it (and failing). Could someone point out what I'm doing wrong?
Public Sub CopyTableToExcel()
Dim xlApp As Excel.Application
Dim xlwb As Excel.Workbook
Dim doc As Word.Document
Dim tbl As Word.Table
Dim lastRow As Long, lastColumn As Integer
Dim tblRange As Word.Range
Dim excelRange As Excel.Range
Set doc = ThisDocument
Set xlApp = CreateObject("Excel.Application")
Set xlwb = xlApp.Workbooks.Add 'Create new workbook
Set tbl = doc.Tables(2)
With tbl:
lastRow = .Rows.Count
lastColumn = .Columns.Count
Set tblRange = .Cell(1, 1).Range
tblRange.End = .Cell(lastRow, lastColumn).Range.End
tblRange.Copy
xlwb.Worksheets(1).Paste
'This part doesn't work, but I'm trying to do something like this:
'Set excelRange = xlwb.Worksheets("Sheet1").Range("A1")
'excelRange.PasteSpecial (xlPasteValuesAndNumberFormats)
End With
Set xlwb = Nothing
Set xlApp = Nothing
Set tbl = Nothing
Set doc = Nothing
End Sub
Thanks for your help!

Microsoft.Office.Interop.Excel - How to save Excel (Visible cells only) to CSV in vb.net

Currently I can save Excel to CSV as code below.
However, it's save all data which is including invisible cells.
Dim excelApplication As Microsoft.Office.Interop.Excel.Application
Dim workbook As Microsoft.Office.Interop.Excel.Workbook
excelApplication = New Microsoft.Office.Interop.Excel.Application
excelApplication.Visible = False
excelApplication.DisplayAlerts = False
workbook = excelApplication.Workbooks.Open(in_InputFilePath)
workbook.SaveAs(in_OutputFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
workbook.Close()
excelApplication.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication)
Dim excelApplication As Microsoft.Office.Interop.Excel.Application
Dim workbook1 As Microsoft.Office.Interop.Excel.Workbook
Dim workbook1worksheet1 As Microsoft.Office.Interop.Excel.Worksheet
Dim workbook1worksheet1range1 As Microsoft.Office.Interop.Excel.Range
Dim workbook2 As Microsoft.Office.Interop.Excel.Workbook
Dim workbook2worksheet1 As Microsoft.Office.Interop.Excel.Worksheet
Dim workbook2worksheet1range1 As Microsoft.Office.Interop.Excel.Range
excelApplication = New Microsoft.Office.Interop.Excel.Application
excelApplication.Visible = False
excelApplication.DisplayAlerts = False
workbook1 = excelApplication.Workbooks.Open(in_InputFilePath)
workbook1worksheet1 = CType(workbook1.Sheets("Sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
workbook1worksheet1.Select(Type.Missing)
workbook1worksheet1range1 = workbook1worksheet1.UsedRange.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeVisible, Type.Missing)
workbook1worksheet1range1.Copy
workbook2 = excelApplication.Workbooks.Add()
workbook2worksheet1 = CType(workbook2.Sheets("Sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
workbook2worksheet1range1 = workbook2worksheet1.Range("A1")
workbook2worksheet1range1.PasteSpecial()
workbook2.SaveAs(in_OutputFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
workbook2.Save()
workbook2.Close()
workbook1.Close()
excelApplication.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook2worksheet1range1)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook2worksheet1)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook2)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook1worksheet1range1)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook1worksheet1)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook1)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication)

Export Word header Bookmark to Excel UserForm1 Textbox

I need VBA Code to get header bookmark in the Excel UserForm1 Textbox. Please assist me. I have got the page count, but not able to get this. I have placed the Code below, which I've tried, but it is not working.
I get error at:
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
and
wst.txtstatementof.Text = "MyBookmark"
Thanks in advance.
Sub ExportBookmarksToExcel()
Dim bk As Bookmark
Dim appXl As Excel.Application
Dim wbk As Excel.Workbook
Dim wst As Excel.Worksheet
Dim x As UserForm1
Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
With appXl
.Visible = True
Set wbk = .Workbooks.Add
Set wst = wbk.UserForm1
wst.txtstatementof.Text = "MyBookmark"
End With
'For each bk In ActiveDocument.Bookmarks
'lRow = lRow + 1
' wst.x.UserForm1.txtstatementof.Text = bk.Name
'wst.Cells(lRow, 2) = bk.Range.Text
'Next bk
'wst.UsedRange.Columns.AutoFit
End Sub
Actually, you weren't far from success. Of course, this must fail:-
Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
You can see that your Excel application is called appXl. Therefore it can't respond to ObjExcel.Workbooks.Open.
Below is the code that works.
Sub ExportBookmarksToExcel()
' MS Word variables:
Dim Bk As Bookmark
Dim R As Long
' MS Excel variables:
Dim appXl As Excel.Application
Dim Wbk As Excel.Workbook
Dim Wst As Excel.Worksheet
Set appXl = CreateObject("Excel.Application")
With appXl
.Visible = True
' Set Wbk = .Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
Set Wbk = .Workbooks.Add
Set Wst = Wbk.Worksheets(1)
' Wst.txtstatementof.Text = "MyBookmark" ' what is "txtstatementof" ?
End With
R = 2 ' keep Row 1 for captions
For Each Bk In ActiveDocument.Bookmarks
Wst.Cells(R, 1) = Bk.Name
Wst.Cells(R, 2) = Bk.Range.Text
R = R + 1
Next Bk
Wst.UsedRange.Columns.AutoFit
End Sub

Can't delete sheet

I'm trying to open a workbook and delete a sheet from it, but it runs the code without errors, and the sheet is still there...
I'm able to modify it, as I changed formulas to values on another sheet.
First of all - Yes, I know the "i" variable is set to do 1 iteration.
Somehow, now when I open the workbook it says it's locked by me - which I don't even know how to do.
So...how can I unlock it? When I go to File-->Info-->Permissions it says 'Anyone can copy, change and modify any part of this workbook.... I can delete the sheet manually as well...
Here's the code:
Sub Change()
Dim wb As Excel.Workbook
Set wb = ThisWorkbook
Dim ws As Excel.Worksheet
Set ws = wb.Sheets("FileSearch Results")
Dim rng As Range
Set rng = ws.UsedRange
Dim cPaths As Integer
cPaths = rng.Column
Dim i As Integer
i = rng.Row
Dim oExcel As Excel.Application
Set oExcel = New Excel.Application
Dim oWB As Workbook
Dim komm As Excel.Worksheet
Dim sh1 As Excel.Worksheet
Do While i < 2
Dim pth As String
pth = ws.Cells(i, cPaths)
Set oWB = oExcel.Workbooks.Open(pth)
Set sh1 = oWB.Worksheets("Sheet1")
With sh1.UsedRange
.Value = .Value
End With
Set komm = oWB.Worksheets("Kommentar")
Application.DisplayAlerts = False
komm.Delete
Application.DisplayAlerts = True
oWB.Close savechanges:=True
i = i + 1
Loop
End Sub
Any ideas?
Sub Change()
Dim wb As Excel.Workbook
Set wb = ActiveWorkbook 'ThisWorkbook
Dim ws As Excel.Worksheet
Set ws = wb.Sheets("FileSearch Results")
Dim rng As Range
Set rng = ws.UsedRange
Dim cPaths As Integer
cPaths = rng.Column
Dim i As Integer
i = rng.row
'Dim oExcel As Excel.Application ***CHANGED***
'Set oExcel = New Excel.Application ***CHANGED***
'Dim oWB As Workbook ***CHANGED***
Dim komm As Excel.Worksheet
Dim sh1 As Excel.Worksheet
Do While i < 2
Dim pth As String
pth = ws.Cells(i, cPaths)
'Set oWB = oExcel.Workbooks.Open(pth) ***CHANGED***
Workbooks.Open (pth) '***ADDED***
Set sh1 = ActiveWorkbook.Worksheets("Sheet1") 'oWB.Worksheets("Sheet1") ***CHANGED***
With sh1.UsedRange
.Value = .Value
End With
Set komm = ActiveWorkbook.Worksheets("Kommentar") 'oWB.Worksheets("Kommentar") ***CHANGED***
Application.DisplayAlerts = False
komm.Delete
Application.DisplayAlerts = True
ActiveWorkbook.Close savechanges:=True 'oWB.Close savechanges:=True ***CHANGED***
i = i + 1
Loop
End Sub
This now opens the workbook and deletes the sheet in the foreground rather than invoking a new instance of Excel and deleting the sheet in the background. This is why the file stays locked, as the new instance which isn't closed by the code, still holds it.
For anyone running into this in the future (like myself), the actual problem is with the mix up in scope when calling Application.DisplayAlerts.
komm is a sheet in oWB, which exists in the new instance of excel oExcel.
Application is a completely different instance and therefor has no effect.
Since the code isn't actually disabling the prompt in the correct instance of excel (oExcel) and it is presumably not visible, the code will just ignore the command and move on.
The simple fix is to use oExcel instead of Application:
Set komm = oWB.Worksheets("Kommentar")
oExcel.DisplayAlerts = False
komm.Delete
oExcel.DisplayAlerts = True

Getting TXT file to Excel

I have the following code to get a text file to an Excel workbook.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
Dim RC(Lines.Length - 1)() As String
For I As Integer = 0 To Lines.Length - 1
RC(I) = Lines(I).Split(CChar(vbTab))
Next
XlRng = XlWkst.Range("a1")
XlRng.Value = RC
XlApp.Visible = True
This method seems to be the fastest way to read and parse a CSV file for dumping to Excel on my computer. it is choking on XlRng.Value = RC. Excel doesn't seem to like RC.
Any ideas for getting Excel to accept the data?
You are setting the value of a cell to an array that contains an entire CSV? I'm guessing this throws a type error.
This is probably more along the lines of what you want.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
For I As Integer = 0 To Lines.Length - 1
XlRng = XlWkst.Range("a1").Offset(I, 0)
Dim RC() As String = Lines(I).Split(CChar(vbTab))
For J As Integer = 0 To RC.Length - 1
XlRng = XlRng.Offset(0, J)
XlRng.Value = RC(J)
Next
Next
XlApp.Visible = True
Did you try simply opening the CSV file directly as in:
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Open("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
XlApp.Visible = True
If you have a valid CSV file do yourself a favor and use a specialised CSV datareader which can handle all the weird problems of CSVs (quotes etc.)
Personally, I like http://kbcsv.codeplex.com/ very much - it is simple to use and fast.
Then just dump the interop part and use the EPPLUS Library to write the data to an excel file - it is magnitudes faster and mind boggingly simple.
Your workflow would look like this:
Use KBCSV to load the data to a datatable.
Use EPPLUS's method "LoadFromDataTable" to generate a new excel file and save it.
Done!