Manipulating Excel files using VB8 - vb.net

My script is pulling some information (filename, date, &c) from a server that contains only (nearly) identical excel files generated by a separate application whenever it is used. The goal is to find out who is using the tool and how often.
I need help with two things: extracting info from within the excel file, and appending the results to the SAME excel file each time it's run instead of creating a new file each time.
Here is what I have...
Imports Excel = Microsoft.Office.Interop.Excel Imports System Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'declare excel objects
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer = 2
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = " File Name "
xlWorkSheet.Cells(1, 2) = " Date Created "
'this should be cell B1
xlWorkSheet.Cells(1, 3) = " Requestor "
'this should be cell B21
xlWorkSheet.Cells(1, 4) = " Lead Type"
'get to directory
For Each strFolder As String In _
My.Computer.FileSystem.GetDirectories("Z:\\...")
'get file names
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(strFolder)
'write to excel worksheet
xlWorkSheet.Cells(i, 1) = strFolder
xlWorkSheet.Cells(i, 2) = infoReader.CreationTime
i += 1
Next
xlWorkSheet.SaveAs("C:\...")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , see file in c:\Documents")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

Instead of creating a new application and workbook, just use activeworkbook, e.g.
replace
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
with
xlWorkBook = xlApp.ActiveWorkbook
xlWorkSheet = xlWorkBook.Sheets("sheetname")
where you replace sheetname with whatever the desired sheet name is.
Alternatively, you could just use ActiveSheet.

Related

Export datatable to Excel (VB window application)

So this is what i've tried. It successfully export but there's NO data. Empty excel. I guess i need to put some code to add row and column but i don't know how. I'm new in this.
Try
'Exporting to Excel.
Dim folderPath As String = dtJelo.Rows(0)("jelly").ToString.Trim
Dim filename As String = "JellyDetails" & current_yyyy & current_mon & ".xlsx"
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
'addrow
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.SaveAs("C:\Users\spongebob\Desktop\" & filename & ".xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created")
Catch ex As Exception
End Try
I am not exactly sure what you are trying to do here, but here is an example of creating an excel file and populating the cells with some data from an array.
Examples of arrays --> Arrays in Visual Basic
So here is the link to the code that you tried to use. Net-informations.com
You were missing the functions to return the year and day as a string to name the file. Also, you were missing the method releaseObject() from the original code that you used.
Test Code
Imports System
Imports System.Windows.Forms
Imports Microsoft.Office.Interop
Namespace WinFormTestApp
Partial Public Class Form1
Inherits Form
Public Sub New()
Call LoadData()
End Sub
Private Sub LoadData()
Try
'Exporting to Excel.
'Dont know where this dtJelo comes from, so I just assigned a folder variable below.
'Dim folderPath As String = dtJelo.Rows(0)("jelly").ToString.Trim
Dim folderPath As String = "C:\temp\"
Dim filename As String = "JellyDetails" & current_yyyy() & current_mon() & ".xlsx"
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)
'Create an array to populate Excel with
Dim myArray(5) As String
myArray(0) = "This is line number 1"
myArray(1) = "This is line number 2"
myArray(2) = "This is line number 3"
myArray(3) = "This is line number 4"
myArray(4) = "This is line number 5"
myArray(5) = "This is line number 6"
'This is where they are adding the code.
xlWorkSheet.Cells(1, 1) = "Column Header Text"
For xx As Integer = 0 To UBound(myArray)
'Add 2 to xx so that you do not overwrite the Column Header
xlWorkSheet.Cells(xx + 2, 1) = myArray(xx)
Next
xlWorkBook.SaveAs($"{folderPath}{filename}", Excel.XlFileFormat.xlWorkbookDefault)
xlWorkBook.Close(True)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
'MsgBox("Excel file created")
MessageBox.Show($"Excel file created , you can find the file at {folderPath}{filename}")
Catch ex As Exception
End Try
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Private Function current_mon() As String
Try
Return String.Format(Now.Month.ToString, "00")
Catch ex As Exception
Return Nothing
End Try
End Function
Private Function current_yyyy() As String
Try
Return Now.Year.ToString
Catch ex As Exception
Return Nothing
End Try
End Function
End Class
End Namespace
Their Code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
If xlApp Is Nothing Then
MessageBox.Show("Excel is not properly installed!!")
Return
End If
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = "Sheet 1 content"
xlWorkBook.SaveAs("d:\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
MessageBox.Show("Excel file created, you can find the file d:\csharp-Excel.xls")
End Sub
'YOU WERE MISSING THIS FUNCTION IN YOUR EXAMPLE
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
Here I propose for your addrow only, you can change range "A1" to other range:
'addrow (you can create function for this, with datatable parameter and range parameter to begin)
Dim IncludeLabel As Boolean = True
For xx = 0 To dtJelo.Rows.Count - 1
For yy = 0 To dtJelo.Columns.Count - 1
If IncludeLabel = True Then
If xx = 0 Then
xlWorkSheet.range("a1").Offset(xx,yy).value=dtJelo.Columns(yy).ColumnName
End If
xlWorkSheet.range("a1").Offset(xx+1,yy).value=dtJelo.Rows(xx)(yy)
Else
xlWorkSheet.range("a1").Offset(xx,yy).value=dtJelo.Rows(xx)(yy)
End If
Next
Next

How can i read excel sheet's text boxes using vb.net (trying to automate a process using uipath invoke code activity)

I'm trying to get the values from Excel TextBoxes using VB.NET, but everything goes wrong. (errors like:" 'Forms' is not a member of Interop " OR "TextBos is not an Interface")
Any Ideas?
Here is my code:
Dim xlApp As Application
Dim xlWorkBooks As Workbooks
Dim xlWorkBook As Workbook
Dim xlWorkSheet As Worksheet
Dim xlWorkSheets As Sheets
Using Microsoft.Vbe.Interop.Forms.TextBox
Dim tb As Forms.TextBox
xlApp = New Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open("C:\Users\pw02318\Documents\UiPath\Accese\exemplu_formular.xlsm")
'xlApp.Visible = True
xlWorkSheets = xlWorkBook.Sheets
xlWorkSheet = CType(xlWorkSheets("New Form"), Worksheet)
For Each shp As Shape In xlWorkSheet.Shapes
Dim oo As OLEObject = CType(xlWorkSheet.OLEObjects(shp.Name), OLEObject)
tb = CType(oo.Object, Microsoft.Vbe.Interop.Forms.TextBox)
console.WriteLine(oo.Name.ToString + tb.Text)
Next shp
End Using
You can read your excel file and put it in a data reader using ExcelDataReader.
first add OpenXml.Excel.Data to your references and import it in your code, then you can write as below:
logDestination = Environment.CurrentDirectory & "\log.txt"
Dim filePaths As String() = Directory.GetFiles(path, "*.xlsx")
If filePaths.Length > 1 Then
File.AppendAllText(logDestination, DateTime.Now & " -----> There Is More Than One xlsx File In The Path Folder" + Environment.NewLine)
ElseIf filePaths.Length = 0 Then
File.AppendAllText(logDestination, DateTime.Now & " -----> There Is No xlsx File In The Path" + Environment.NewLine)
Environment.[Exit](0)
End If
Dim dt = New DataTable()
Dim reader As var = New ExcelDataReader(filePaths(0), 1, True)
dt.Load(reader)

How do I declare my active Excel workbook and active Excel worksheet as a variable?

I am trying to figure how to set the active workbook and active sheet as a variable I can reference later. I have my script set up, and I placed ????'s in the areas where I assume I would put the reference.
Any suggetsions?
Dim oXL As Application
Dim oWB As Microsoft.Office.Interop.Excel.Workbook
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim oRng As Microsoft.Office.Interop.Excel.Range
oWB = ????
oSheet = ?????
Added info from comment to Karen Payne's answer:
I am trying to reference an existing one I already have open, that is
the active window at the time of using my application.
i.e.: How can I attach to an open Excel instance and retrieve a reference to the ActiveWorkbook?
Perhaps the following will help. It is a demo that sets the active sheet in xlWorkSheet that can be used as you see fit.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module SetDefaultWorkSheetCode
Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
xlWorkSheet.Activate()
xlWorkSheet.SaveAs(FileName)
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
With those Excel objects, you have to assign values to them using the "Set" keyword. For example:
Set oWB = ActiveWorkbook
Here are two techniques for attaching to a running Excel instance. I think the method shown in 'Button1_Click' is one you are seeking, but I also showed second method that looks in the Running Object Table (ROT) for a matching Workbook name.
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop
Public Class Form1
Private WithEvents ExcelCleanUpTimer As New Timer With {.Interval = 100}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim app As Excel.Application
Try ' to attach to any Excel instance
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Catch ex As Exception
MessageBox.Show("No Excel instances found")
Exit Sub
End Try
' take over responsibility for closing Excel
app.UserControl = False
app.Visible = False
Dim activeWB As Excel.Workbook = app.ActiveWorkbook
Dim activeSheet As Object = app.ActiveSheet
' determine if ActiveSheet is a Worksheet or Chart
' if it is a Worksheet, activeChart is Nothing
' if it is a Chart, activeWorksheet is Nothing
Dim activeWorksheet As Excel.Worksheet = TryCast(activeSheet, Excel.Worksheet)
Dim activeChart As Excel.Chart = TryCast(activeSheet, Excel.Chart)
If activeWorksheet IsNot Nothing Then
For Each cell As Excel.Range In activeWorksheet.Range("A1:A20")
cell.Value2 = "hello"
Next
End If
'shut Excel down, don't save anything
app.DisplayAlerts = False
app.Workbooks.Close()
app.Quit()
' using a timer lets any ComObj variables in this method go out of context and
' become eligible for finalization. GC's call to RCW wrapper finalizer will
' release its reference counts on Excel
ExcelCleanUpTimer.Start()
End Sub
Private Sub ExcelCleanUpTimer_Tick(sender As Object, e As EventArgs) Handles ExcelCleanUpTimer.Tick
ExcelCleanUpTimer.Stop()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' if this is a saved Workbook, the path will be the full file path
Dim path As String = "Book1" ' or the full file path to a workbook including the extension
Dim activeWorkbook As Excel.Workbook = Nothing
Try
' this technique differs for Marshal.GetActiveObject in that if the path
' is a valid file path to an Excel file and Excel is not running, it will
' launch Excel to open the file.
activeWorkbook = CType(Marshal.BindToMoniker(path), Excel.Workbook)
Catch ex As Exception
' an exception will be throw if 'path' is not found in the Runinng Object Table (ROT)
MessageBox.Show(path & " not found")
Exit Sub
End Try
Dim app As Excel.Application = activeWorkbook.Application
app.Visible = True
app.UserControl = True
' the wb window will be hidden if opening a file
activeWorkbook.Windows(1).Visible = True
ExcelCleanUpTimer.Start()
End Sub
End Class
Sorry about my last answer.. I didn't see that you were trying to do it in .NET. Anyway, just like in the context of Excel, you have to first open or create all of the workbooks that you want to work with. If you already have it open, then you can use the file name of the workbook you want to assign it to a workbook variable..
xlWorkbook = xlApp.Workbooks.Item("filename of the workbook already open")
Here is the same code, partly commented out as to the activate part and I added in code to show how to get the current active sheet.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module SheetCode
Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
'
' Here I added how to get the current active worksheet
'
Dim ActiveSheetInWorkBook As Excel.Worksheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)
Console.WriteLine(ActiveSheetInWorkBook.Name)
Runtime.InteropServices.Marshal.FinalReleaseComObject(ActiveSheetInWorkBook)
ActiveSheetInWorkBook = Nothing
'For x As Integer = 1 To xlWorkSheets.Count
' xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
' If xlWorkSheet.Name = SheetName Then
' xlWorkSheet.Activate()
' xlWorkSheet.SaveAs(FileName)
' Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
' xlWorkSheet = Nothing
' Exit For
' End If
' Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
' xlWorkSheet = Nothing
'Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module

from data textbox to excel vb.net

I have this code that allows me to export the data contained in the two TextBoxs in an excel spreadsheet, the problem is that the excel file is not created. I put the two statements are not working for rescuing comment below, maybe someone can test it and tell me why it is wrong.
Dim objExcel As New Excel.Application ' Represents an instance of Excel
Dim objWorkbook As Excel.Workbook 'Represents a workbook object
Dim objWorksheet As Excel.Worksheet 'Represents a worksheet object
objWorkbook = objExcel.Workbooks.Add
objWorksheet = CType(objWorkbook.Worksheets.Item(1), Excel.Worksheet)
'This form contains two text boxes, write values to cells A1 and A2
objWorksheet.Cells(1, 1) = TextBox1.Text
objWorksheet.Cells(2, 1) = TextBox2.Text
objWorkbook.Close(False)
'objWorkbook.Save()
'or
'objWorkbook.SaveAs("C:\Temp\Book1.xls")
objExcel.Quit()
Code is tried and tested
Your issue can be from a few different things that I can see. I provided a few issues that I could see from your code you posted.
Your calling .Close before actually saving the workbook.
You didn't specify the "FileFormat" in the save function.
Your not quitting the instance of Excel.
It's important to release ALL objects of Excel you use. If not, it's being held up in memory and will not be released.
Code Below
Dim xlApp As New excel.Application
Dim xlWorkBook As excel.Workbook
Dim xlWorkSheet As excel.Worksheet
Try
xlApp.DisplayAlerts = False
xlWorkBook = xlApp.Workbooks.Add
xlWorkSheet = DirectCast(xlWorkBook.Sheets("Sheet1"), excel.Worksheet)
xlApp.Visible = False 'Don't show Excel; we can and we don't have too
xlWorkSheet.Cells(1, 1) = TextBox1.Text
xlWorkSheet.Cells(2, 1) = TextBox2.Text
xlWorkBook.SaveAs("C:\Temp\Book1.xls", FileFormat:=56) 'Save the workbook
xlWorkBook.Close() 'Close workbook
xlApp.Quit() 'Quit the application
'Release all of our excel objects we used...
ReleaseObject(xlWorkSheet)
ReleaseObject(xlWorkBook)
ReleaseObject(xlApp)
Catch ex As Exception
End Try
Method to Release Excel Objects
Public Shared Sub ReleaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

Modifying a template based excel in VB.NET

I am tyring to run code like this
xlWorkSheet.Cells(rownumber, 1) = "Some Value"
the problem is when I open the excel document the cell value is not updated.
any help will be appreciated
I use the following code to open the file
Dim pathtofile As String = Server.MapPath("~/UserControls/Upload/MyUpload.xlsx")
Dim xlApp As Excel.Application =New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlworkbooks As Excel.Workbooks
Dim xlWorksheets As Excel.Worksheets
Dim misValue As Object = System.Reflection.Missing.Value
Dim xlWorkSheet As Excel.Worksheet = Nothing
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlworkbooks = xlApp.Workbooks
xlWorkBook = xlworkbooks.Open(pathtofile )
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
You need to save, close, and release the com objects to make sure excel doesn't remain running as a process.
Sub save(filename As String) ' Saves the sheet under a specfic name
xlWorkBook.SaveAs(filename)
End Sub
Sub closexl()
xlWorkBooks.Close()
xlApp.Quit()
End Sub
Sub cleanup() ' Releases all of the com objects to object not have excel running as a process after this method finishes
GC.Collect()
GC.WaitForPendingFinalizers()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End Sub