I'm currently working on a program for my company that will be used to communicate various information between users, among other things that aren't important at the moment. One of the things that is going to be communicated is a daily tasks checklist. Basically, the intent is to have a check list that syncs between all users, so if one user checks off a task, everyone else can see that the task has been completed.
So far what I have done is I have created a DataGrid object to hold the check boxes. The box starts empty, but when the program loads, the following code is run, which populates the list.
Private Sub chkListPop()
If System.IO.File.Exists(chkListPath) Then
Dim newChk As CheckBox
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBooks As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim rng As Microsoft.Office.Interop.Excel.Range
Dim r As Byte
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBooks = xlApp.Workbooks.Open(chkListPath)
xlWorkSheet = xlWorkBooks.Worksheets("Tasks")
rng = xlWorkSheet.Range("A2")
r = 0
Do While rng.Offset(r).Value <> ""
chkListContainer.Items.Add(New Controls.CheckBox)
newChk = chkListContainer.Items.Item(r)
newChk.Content = rng.Offset(r).Value
Try
If rng.Offset(r, 1).Value = True Then
newChk.IsChecked = True
End If
Catch
End Try
r = r + 1
Loop
xlApp.DisplayAlerts = False
xlWorkBooks.Save()
xlWorkBooks.Close()
xlApp.DisplayAlerts = True
xlApp.Quit()
End If
End Sub
Basically, the sub reads an excel file and, for each line in the file, creates a checkbox with the true false value in the second column. I imagine there has to be a more elegant solution to do this. I am not a programmer by training, so I have limited knowledge on topics this "complex". Whats a better way to do this other than using an excel file? Should I use an Access database or and SQL database instead? This code works, but I just feel like its wrong somehow.
Additionally, I am having trouble figuring out how to update the file when someone checks off a task. For now I just have a timer running, and every X minutes, the program updates the excel file. Here's the code for how that works:
Public Sub chkListSendData()
If System.IO.File.Exists(chkListPath) Then
Dim newChk As CheckBox
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBooks As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim rng As Microsoft.Office.Interop.Excel.Range
Dim r As Byte
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBooks = xlApp.Workbooks.Open(chkListPath)
xlWorkSheet = xlWorkBooks.Worksheets("Tasks")
rng = xlWorkSheet.Range("A2")
r = 0
Do While rng.Offset(r).Value <> ""
Try
newChk = chkListContainer.Items.Item(r)
Catch
chkListContainer.Items.Add(New Controls.CheckBox)
newChk = chkListContainer.Items.Item(r)
newChk.Content = rng.Offset(r).Value
End Try
If newChk.IsChecked Then
rng.Offset(r, 1).Value = True
End If
r = r + 1
Loop
xlApp.DisplayAlerts = False
xlWorkBooks.Save()
xlWorkBooks.Close()
xlApp.DisplayAlerts = True
xlApp.Quit()
End If
End Sub
Public Sub chkListGetData()
If System.IO.File.Exists(chkListPath) Then
Dim newChk As CheckBox
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBooks As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim rng As Microsoft.Office.Interop.Excel.Range
Dim r As Byte
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBooks = xlApp.Workbooks.Open(chkListPath)
xlWorkSheet = xlWorkBooks.Worksheets("Tasks")
rng = xlWorkSheet.Range("A2")
r = 0
Do While rng.Offset(r).Value <> ""
Try
newChk = chkListContainer.Items.Item(r)
Catch
chkListContainer.Items.Add(New Controls.CheckBox)
newChk = chkListContainer.Items.Item(r)
newChk.Content = rng.Offset(r).Value
End Try
Try
If rng.Offset(r, 1).Value = True Then
newChk.IsChecked = True
End If
Catch
End Try
r = r + 1
Loop
xlApp.DisplayAlerts = False
xlWorkBooks.Close()
xlApp.DisplayAlerts = True
xlApp.Quit()
End If
End Sub
Private Sub chkTimer()
Dim dispatcherTimer As DispatcherTimer = New DispatcherTimer()
AddHandler dispatcherTimer.Tick, AddressOf OnTimedEvent
dispatcherTimer.Interval = New TimeSpan(0, 1, 0)
dispatcherTimer.Start()
End Sub
Private Sub OnTimedEvent(ByVal sender As Object, ByVal e As EventArgs)
chkListGetData()
chkListSendData()
End Sub
In my testing, this has worked fine, but I have a feeling that when lots of people are using the program, this will not work so well when multiple people attempt to update the file at the same time. If I'm wrong and this code is perfect, that's great, but I doubt that is the case. If there's a better way to handle this kind of thing, I would love to learn how to implement it in this program.
Thanks, in advance, for your help.
Related
I am trying to evaluate if specific cell value in an excel table is "" to use in an if statement in my VB.NET application. I modified the code that I use for writing to excel, but it doesn't work to get the cell value. The code I have:
Sub Excel_LoadProjectsSchedule()
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
Dim ProjectFinished as boolean
'Set variables
Result = xlWorkSheet.Cells.Find(ProjectNumber, LookAt:=Excel.XlLookAt.xlWhole)
If xlWorkSheet.Cells(Result.Row, 3).value = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
'Save and close
xlApp.DisplayAlerts = False
xlWorkBook.Close(SaveChanges:=True)
xlApp.Quit()
End Sub
Error is on
If xlWorkSheet.Cells(Result.Row, 3).value = "" Then
And it says "System.MissingMemberException: 'Public member 'value' on type 'Range' not found.'
"
I do have
Public xlApp As Excel.Application = Nothing
Public xlWorkBook As Excel.Workbook = Nothing
Public xlWorkSheet As Excel.Worksheet = Nothing
Outside the sub in this module.
What am I doing wrong, could someone, please, help me solve this one?
I did some casting so the compiler can recognize the types.
Sub Excel_LoadProjectsSchedule(ProjectNumber As Integer)
Dim xlApp = New Excel.Application
Dim xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
Dim xlWorkSheet = DirectCast(xlWorkBook.Worksheets("sheet1"), Excel.Worksheet)
Dim ProjectFinished As Boolean
'Set variables
Dim Result = xlWorkSheet.Cells.Find(ProjectNumber, LookAt:=Excel.XlLookAt.xlWhole)
Dim row = Result.Row
Dim cell = DirectCast(xlWorkSheet.Cells(row, 3), Excel.Range)
If cell.Value Is Nothing Then
'What do you want to do?
Else
If cell.Value.ToString = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
End If
'Save and close
xlApp.DisplayAlerts = False
xlWorkBook.Close(SaveChanges:=True)
xlApp.Quit()
End Sub
I think if you specifically want to check contents in the 3rd Column of the Row with that Projectnumber you're not far away from the Solution.
I only tested it inside of VBA but something along the Lines of:
Sub Excel_LoadProjectsSchedule()
Dim xlWorksheet As Worksheet, Result As Range, ProjectFinished As Boolean
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
Set xlWorkSheet = xlWorkBook.Worksheets("sheet1")
'Set variables
Set Result = xlWorksheet.Cells.Find(Projectnumber, LookIn:=Excel.XlLookin.xlValues, LookAt:=Excel.XlLookAt.xlWhole)
if not Result is nothing then
If Cells(Result.Row, 3).Value = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
End Sub
The Problem being, that "Result" hasn't been asigned to a Range, so your code coudn't access the Row Property.
If looking for a certain cell in certain row .
Dim AppExcel As Object
Dim workBook As Object
AppExcel = CreateObject("Excel.Application")
workBook = AppExcel.Workbooks.Open("C:\SO\SO.xlsx")
AppExcel.Visible = False
Worksheets = workBook.worksheets
If Worksheets("Blad1").Cells(2, 3).text = "" Then
MessageBox.Show("Empty")
Else
MessageBox.Show("Text")
End If
Then the close part
I am running a code to export a datatable to Excel. Since this is taking a while I dont want to confuse the user and display an image
Dim _excel As New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
PictureLoading.Visible = True
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = GetTableForCompleteArchive()
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
PictureLoading.Refresh()
For Each dc In dt.Columns
colIndex += 1
_excel.Cells(1, colIndex) = dc.ColumnName
Next
PictureLoading.Refresh()
For Each dr In dt.Rows
rowIndex += 1
colIndex = 0
For Each dc In dt.Columns
colIndex += 1
_excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
PictureLoading.Refresh()
wSheet.Columns.AutoFit()
Dim strFileName As String = Application.StartupPath & "\Export.xlsx" '"C:\datatable.xlsx"
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
PictureLoading.Refresh()
wBook.SaveAs(strFileName)
wBook.Close()
_excel.Quit()
PictureLoading.Visible = False
The problem is the image freezes and is not animating. Is there a way to get the image animating while waiting for the process?
Private Sub TotalArchiveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EXCELToolStripMenuItem.Click
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.WorkerReportsProgress = True
'call this method to start your asynchronous Task.
BackgroundWorker1.RunWorkerAsync()
'display the loading image
PictureLoading.Visible = True
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'call the function to export to Excel
Export2Excel()
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
'' This event is fired when your BackgroundWorker exits.
'' It may have exitted Normally after completing its task,
'' or because of Cancellation, or due to any Error.
PictureLoading.Visible = False
End Sub
My function is run from inside the Backgroundworker_DoWork. The image is set to visible when I click TotalArchiveToolStripMenuItem and set to not visible when the BackgroundWorker is completed.
I am exporting my data from visual studio data grid view into excel and I want to know how to add/save new sheets into an existing excel file.
If using OleDb the use SQL to create a sheet
Public Module Demo
Public Sub DemoOleDbCreateXls_WithHeaders()
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "CREATE TABLE Members(FirstName CHAR(255),LastName CHAR(255),JoinedYear INT)"
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Members (FirstName,LastName,JoinedYear) VALUES ('Kevin','Gallagher',2013)"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Officiers(FirstName CHAR(255),LastName CHAR(255),Rank CHAR(255))"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Officiers (FirstName,LastName,Rank) VALUES ('Joan','Gallagher','AAA')"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Test1(Description CHAR(255),Amount Double)"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Test1 (Description,Amount) VALUES ('Dues',12.99)"
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
End Module
Using Excel automation
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Module Demo
Public Sub CreateSheetIfNeeded(ByVal FileName As String, ByVal SheetName As String)
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
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/Next finds our sheet
'
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
Dim workSheet As Excel.Worksheet = Nothing
Dim xlNewSheet As Excel.Worksheet = Nothing
If Proceed Then
' do work, sheet exists
Else
workSheet = CType(xlWorkSheets(1), Excel.Worksheet)
xlNewSheet = DirectCast(xlWorkSheets.Add(workSheet), Excel.Worksheet)
xlNewSheet.Name = SheetName
End If
xlWorkBook.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseExcelObject(xlNewSheet)
ReleaseExcelObject(workSheet)
ReleaseExcelObject(xlWorkSheets)
ReleaseExcelObject(xlWorkSheet)
ReleaseExcelObject(xlWorkBook)
ReleaseExcelObject(xlWorkBooks)
ReleaseExcelObject(xlApp)
Else
' file does not exists
End If
End Sub
Private Sub ReleaseExcelObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Module
hi i have a problem regarding my code in vb.net it seems this code is correct but the result is only generating the file but not the data inside the excel file i had created here is my code
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
Dim j As Integer
Try
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add()
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("C:\Users\CLB Engineering Mkt\Desktop\moveoutreport.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Success")
Catch ex As Exception
MsgBox(ex.Message)
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
and also my datatable in gridview was like this.....
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New MySqlDataAdapter("select stock_number, item_description, quantity, unit_measure, customers_name, f_date from tbl_move_out", con)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
can you please help me regarding this ? Thank You in Advance
I have been unsuccessful in setting the row height and column widths of an excel spreadsheet from within a visual basic application.
I have a visual basic application where I have data in my clipboard. I copy that code to an instance of excel and then have excel save the resulting spreadsheet and then excel closes. I am trying to programmatically set the row heights and cell widths prior to saving the spreadsheet but have been unable to do so. This is the code that I am executing:
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oXL = CreateObject("Excel.Application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
oSheet.Paste()
oSheet.Cells.Select()
oSheet.Selection.RowHeight = 11.4
oSheet.Cells.EntireColumn.AutoFit()
oSheet = Nothing
oWB.Close(True, SaveFileDialog1.FileName)
oWB = Nothing
oXL.Quit()
oXL = Nothing
MsgBox("Finished!")
End If
The application runs without the oSheet.Cells.Select(), oSheet.Selection.RowHeight = 11.4, and oSheet.Cells.EntireColumn.AutoFit()
lines. With these lines, I get this error dialog message:
Public member 'Selection' on type 'Worksheet' not found.
When I trace the program in Visual Studio, the oSheet.Paste() command executes and the oSheet.Cells.Select() command executes. The exception is generated when I try to execute the oSheet.Selection.RowHeight = 11.4 command.
Any assistance would be greatly appreciated.
Jonathan
The following is not late binding, it's early binding but the pattern should work with minor code changes.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Imports System.IO
Public Class Operations
Public HasError As Boolean
Public ErrorMessage As String
''' <summary>
'''
''' </summary>
''' <param name="FileName">Path and file name for Excel file</param>
''' <param name="SheetName">Sheet name to work on</param>
''' <param name="RowHeight">Used to set row height in SheetName</param>
''' <returns></returns>
Public Function SetWidthHeight(
ByVal FileName As String,
ByVal SheetName As String,
ByVal RowHeight As Integer) As Boolean
If File.Exists(FileName) Then
Dim Proceed As Boolean = False
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
Dim xlCells As Excel.Range = 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
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
xlCells = xlWorkSheet.Cells
xlCells.PasteSpecial()
Dim EntireRow As Excel.Range = xlCells.EntireRow
'
' Set row height
'
EntireRow.RowHeight = RowHeight
Dim ColRange = xlCells.EntireColumn
'
' Auto fit all columns
'
ColRange.AutoFit()
ReleaseComObject(ColRange)
ReleaseComObject(xlCells)
ReleaseComObject(EntireRow)
Else
HasError = True
ErrorMessage = SheetName & " not found."
End If
xlWorkSheet.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
HasError = True
ErrorMessage = "'" & FileName &
"' not located. Try one of the write examples first."
End If
Return HasError
End Function
Private Sub ReleaseComObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Class