Cell date format in excel showing datetime - vb.net

I have an application that can retrieves the install date and save it at a datagridview column with the format of date only.
But when I tried to export it to an excel file, even when I tried to format the cell, it still shows me datetime instead of date only for some of the data.
The code for exporting is shown below. btw I'm using vb.net
'reportFile : True = IE_Version_Report.xlsx False = Data.xlsx
Sub ExportData(reportFile)
Dim dSet As New DataSet
dSet.Tables.Add()
For i As Integer = 0 To DataGridView1.ColumnCount - 1
dSet.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
Next
Dim dr As DataRow
For i As Integer = 0 To DataGridView1.RowCount - 1
dr = dSet.Tables(0).NewRow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
dr(j) = DataGridView1.Rows(i).Cells(j).Value
Next
dSet.Tables(0).Rows.Add(dr)
Next
Dim Ex As Microsoft.Office.Interop.Excel.Application
Dim Wb As Microsoft.Office.Interop.Excel.Workbook
Dim Ws As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Ex = New Microsoft.Office.Interop.Excel.Application
Wb = Ex.Workbooks.Add(misValue)
Ws = Wb.Sheets("sheet1")
Dim dt As DataTable = dSet.Tables(0)
Dim col, row As Integer
Dim rawData(dt.Rows.Count, dt.Columns.Count - 1) As Object
For col = 0 To dt.Columns.Count - 1
rawData(0, col) = dt.Columns(col).ColumnName.ToUpper
Next
For col = 0 To dt.Columns.Count - 1
For row = 0 To dt.Rows.Count - 1
rawData(row + 1, col) = dt.Rows(row).ItemArray(col)
Next
Next
Dim finalColLetter As String = String.Empty
finalColLetter = ExcelColName(dt.Columns.Count)
Dim excelRange As String = String.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1)
Ws.Range(excelRange, Type.Missing).Value2 = rawData
Ws.Range("A1:L1").EntireColumn.AutoFit() 'columns in excel file will autofit according to the data
Dim num As Integer = DataGridView1.Rows.Count + 1
'set the format for dates in these few columns
Ws.Range("D2:D" & num).NumberFormat = "dd/mm/yyyy;#"
Ws.Range("F2:F" & num).NumberFormat = "dd/mm/yyyy;#"
Ws.Range("H2:H" & num).NumberFormat = "dd/mm/yyyy;#"
Ws.Range("J2:J" & num).NumberFormat = "dd/mm/yyyy;#"
Ws.Range("L2:L" & num).NumberFormat = "dd/mm/yyyy;#"
Ws = Nothing
If reportFile = True Then
fileExported = True
If System.IO.File.Exists(FolderPath & "\MSOffice_Report.xlsx") Then
System.IO.File.Delete(FolderPath & "\MSOffice_Report.xlsx")
End If
Wb.SaveAs(FolderPath & "\MSOffice_Report.xlsx")
Else
fileExported = False
If System.IO.File.Exists("C:\Install\MSData.xlsx") Then
System.IO.File.Delete("C:\Install\MSData.xlsx")
End If
Wb.SaveAs("C:\Install\MSData.xlsx")
SetAttr("C:\Install\MSData.xlsx", vbHidden)
End If
Wb.Close(True)
Wb = Nothing
Ex.Quit()
Ex = Nothing
GC.Collect()
End Sub
Public Function ExcelColName(ByVal Col As Integer) As String
If Col < 0 And Col > 256 Then
MsgBox("Invalid Argument", MsgBoxStyle.Critical)
Return Nothing
Exit Function
End If
Dim i As Int16
Dim r As Int16
Dim S As String
If Col <= 26 Then
S = Chr(Col + 64)
Else
r = Col Mod 26
i = System.Math.Floor(Col / 26)
If r = 0 Then
r = 26
i = i - 1
End If
S = Chr(i + 64) & Chr(r + 64)
End If
ExcelColName = S
End Function
Sorry if it's a very stupid question but I really don't know what's wrong with it.
Thanks!

Excel does not recognise dates earlier than 1/1/1900 and will treat a value like 11/11/1111 12:00:00 AM as text. See how the dates are right-aligned and the text is left aligned in your screenshot?
Text will not be affected by the number formatting you apply to show only the date of the values.
Depending on what you want to achieve, you need to adjust your code to handle the text values differently. Replace them with 1/1/1900 or some such.

Related

VBA Event Handler To Return Value

I have an event handler Sub that listens for a response message from the Bloomberg API, and stores it in a Dd array.
According to MSDN, event handlers must be subs, but I would like to do further analysis on the data in my main method.
How can I reference the array created in the event handler, such that I can continue to process the data?
Event handler:
Private Sub session_ProcessEvent(ByVal obj As Object)
On Error GoTo errHandler
Dim eventObj As blpapicomLib2.Event
Set eventObj = obj
If Application.Ready Then
If eventObj.EventType = PARTIAL_RESPONSE Or eventObj.EventType = RESPONSE Then
Dim it As blpapicomLib2.MessageIterator
Set it = eventObj.CreateMessageIterator()
Dim numResponse As Integer
numResponse = 0
Dim data() As Variant
Do While it.Next()
numResponse = numResponse + 1
Dim msg As Message
Set msg = it.Message
Dim securityData As Element
Dim securityName As Element
Dim fieldData As Element
Set securityData = msg.GetElement("securityData")
Set securityName = securityData.GetElement("security")
Set fieldData = securityData.GetElement("fieldData")
Sheet1.Cells(currentRow, 4).Value = securityName.Value
Dim numDates As Integer
Dim numFields As Integer
numDates = fieldData.NumValues
numFields = fieldData.GetValue(0).NumElements
ReDim data(numDates, numFields, numResponse)
Dim b As Integer
For b = 0 To numDates - 1
Dim fields As blpapicomLib2.Element
Set fields = fieldData.GetValue(b)
Dim a As Integer
For a = 0 To numFields - 1
Dim field As Element
Set field = fields.GetElement(a)
data(b, a, numResponse) = field.Value
Sheet1.Cells(currentRow, a + 5).Value = data(b, a, numResponse)
Next
currentRow = currentRow + 1
Next b
Loop
' skip a row for next security
currentRow = currentRow + 1
End If
End If
Exit Sub
errHandler:
MsgBox Err.Description
End Sub
...and the sub I would like to process the array in here...
Public Sub RefDataExample()
' Calculate the number of securities and fields
Dim numSecurity As Integer
Dim numFields As Integer
numSecurity = 0
numFields = 0
' clear data area
Range("D4", "H60000").Clear
Do While Cells(numSecurity + 4, 1).Value <> ""
numSecurity = numSecurity + 1
Loop
Do While Cells(numFields + 4, 2).Value <> ""
numFields = numFields + 1
Loop
Dim sSecurity() As String
Dim sFields() As Variant
ReDim sSecurity(0 To numSecurity - 1) As String
ReDim sFields(0 To numFields - 1) As Variant
Dim i As Integer
For i = 0 To numSecurity - 1
sSecurity(i) = Cells(i + 4, 1).Value
Next i
For i = 0 To numFields - 1
sFields(i) = Cells(i + 4, 2).Value
Next i
bbControl.MakeRequest sSecurity, sFields
'Process response array here
End Sub
Remove
Dim data() As Variant
from within all the subs it currently appears in (like from within your session_ProcessEvent())
and place
Public data As Variant
at the top of the module containing your sub (actually you can place it at the top of any module you like)
and you'll have ”data” visible from all subs/functions of your project

'Index was out of range. Must be non-negative and less than the size of the collection

I have a data grid view , I want to export to Excel.
I want to export only the Visible columns in the data grid view.
But I keep getting this error.
Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim ExcelApp As Excel.Application
Dim ExcelWorkBk As Excel.Workbook
Dim ExcelWorkSht As Excel.Worksheet
Dim i As Integer
Dim j As Integer
ExcelApp = New Excel.Application
ExcelWorkBk = ExcelApp.Workbooks.Add()
ExcelWorkSht = ExcelWorkBk.Sheets("Sheet1")
Dim columnsCount As Integer = DGVinfo3.Columns.Count
For i = 0 To DGVinfo3.RowCount - 1
If DGVinfo3.Columns(i).Visible = True Then
For j = 0 To DGVinfo3.ColumnCount - 1
For k As Integer = 0 To DGVinfo3.Columns.Count + 1
If DGVinfo3.Columns(k).Visible = True Then
ExcelWorkSht.Cells(1, k) = DGVinfo3.Columns(k - 1).HeaderText
ExcelWorkSht.Cells(1, k).Font.Bold = True
ExcelWorkSht.Cells(1, k).interior.color = RGB(192, 203, 219)
ExcelWorkSht.Cells(i + 1, j + 1) = DGVinfo3(j, i).Value
End If
Next
Next
End If
Next
End Sub
I keep getting this error:
System. Argument Out Of Range Exception: 'Index was out of range. Must be
non-negative and less than the size of the collection.'
Here is where I get the Error:
ExcelWorkSht.Cells(1, k) = DGVinfo3.Columns(k - 1).HeaderText
Just loop the rows and inside that loop each column. Also because the hidden columns won't be exported to Excel, it's probably best to keep track of the Excel columns in a separate variable:
Dim xlColumn As Integer
For i = 0 To DGVinfo3.RowCount - 1
xlColumn = 0
For j = 0 To DGVinfo3.ColumnCount - 1
If DGVinfo3.Columns(j).Visible = True Then
xlColumn += 1
If i = 0 Then
'You only need to set the column headers for the first row
ExcelWorkSht.Cells(1, xlColumn) = DGVinfo3.Columns(j).HeaderText
ExcelWorkSht.Cells(1, xlColumn).Font.Bold = True
ExcelWorkSht.Cells(1, xlColumn).interior.color = RGB(192, 203, 219)
End If
'i + 2 because the header is row 1
ExcelWorkSht.Cells(i + 2, xlColumn) = DGVinfo3(i, j).Value
End If
Next
Next

How to unlock columns in Excel using VB.Net?

Good Morning
I have a program in VB.Net that exports a file from Datagridview into Excel file
and it looks like this.
My goal here is how can I lock some columns? based on the Image above? Lock all columns except the column that has a color yellow? I mean all the columns except the yellow are uneditable.
Here is my code in exporting excel
Try
If DataGridView1.Rows.Count = 0 Then
MsgBox("Nothing to Export")
Else
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim J As Integer
Dim rowIndex As Integer = 1
Dim total As Double = 0
Dim indexTotal As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
rowIndex += 2
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(rowIndex, column.Index + 1) = column.HeaderText
Next
.Range(.Cells(rowIndex, 1), .Cells(rowIndex, DataGridView1.Columns.Count)).Font.Bold = True
rowIndex += 1
For i = 0 To Me.DataGridView1.RowCount - 1
.cells(rowIndex, 1) = Me.DataGridView1.Rows(i).Cells("ItemCode").Value
For J = 1 To DataGridView1.Columns.Count - 1
If IsNumeric(DataGridView1.Rows(i).Cells(J).Value) Then
.cells(rowIndex, J + 1).NumberFormat = "#,##0.00"
.cells(rowIndex, J + 1) = DataGridView1.Rows(i).Cells(J).Value
Else
.cells(rowIndex, J + 1) = DataGridView1.Rows(i).Cells(J).Value
End If
'You can test also by index for example : if J = indexofTotalColumn then
If DataGridView1.Columns(J).Name = "Total" Then
total += DataGridView1.Rows(i).Cells(J).Value
indexTotal = J
End If
Next
rowIndex += 1
.Columns("A:Z").EntireColumn.AutoFit()
.Columns("L").ColumnWidth = 0
.cells(5).Locked = False
Next
.Protect("fakepwd")
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End If
Catch
End Try
TYSM for help
Set the Locked property of the cell to false, where J+1 is the desired column number.
For example to unlock column 5 :
For J = 1 To DataGridView1.Columns.Count - 1
If J=5 then
.cells(rowIndex, J + 1).Locked=False
End if
If IsNumeric(DataGridView1.Rows(i).Cells(J).Value) Then
..........
In the code, once you are done populating data in sheet, protect the sheet
Next
.Protect ("fakepwd")
End With

Multiple datagrids to one excel sheet

I have the below code which will transfer the records from my datagrid to my excel spreadsheet.
Currently this code works for one datagrid to an excel sheet. Now I need to improve the below code so that it can work for multiple datagrids. I want help to extend this code so that I can pull the records from 3 data grids to the same excel sheet one below another.
Dim excel As Microsoft.Office.Interop.Excel.Application
Try
excel = New Microsoft.Office.Interop.Excel.Application
excel.Workbooks.Open("C:\Satish\TestExcel\vbexcel.xlsx")
Dim i As Integer, j As Integer
Dim diff As Integer = 1
' if you want column header from dgv elese omit the block
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For j = 0 To DataGridView1.ColumnCount - 1
excel.Worksheets(1).cells(1, j + 1) = DataGridView1.Columns(j).Name
Next
diff += 1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For i = 0 To DataGridView4.RowCount - 1
If DataGridView4.Rows(i).IsNewRow = False Then
For j = 0 To DataGridView4.ColumnCount - 1
excel.Worksheets(1).cells(i + diff, j + 1) = DataGridView4.Item(j, i).Value
Next
End If
Next
excel.Worksheets(1).select()
excel.ActiveWorkbook().Save()
excel.Workbooks.Close()
excel.Quit()
excel = Nothing
Catch ex As System.Runtime.InteropServices.COMException
MessageBox.Show("Error accessing Excel: " + ex.ToString())
Catch ex As Exception
MessageBox.Show("Error: " + ex.ToString())
End Try
Try this code:
Dim intExcelRow As Integer = 1
For i As Integer = 1 To 3
Dim YourDataGridView As DataGridView = Me.Controls("YourDataGridView" & i)
'header of the first DataGridView only
'remove If i = 1 if you need to print 3 different headers
If i = 1 Then
For intColumn = 0 To YourDataGridView.ColumnCount - 1
excel.Worksheets(1).cells(intExcelRow, intColumn + 1) = YourDataGridView.Columns(intColumn).Name
Next intColumn
intExcelRow = intExcelRow + 1
End If
For intRow = 0 To YourDataGridView.RowCount - 1
If YourDataGridView.Rows(intRow).IsNewRow = False Then
For intColumn = 0 To YourDataGridView.ColumnCount - 1
excel.Worksheets(1).cells(intExcelRow, intColumn + 1) = YourDataGridView.Item(intColumn, intRow).Value
Next intColumn
intExcelRow = intExcelRow + 1
End If
Next intRow
Next i

Excel cell Format Changes in text

I have use microsoft Excel Sheet ..I've fell different Values in excel sheet there is no problem..
but i've fell some numeric Columns like this (00023785678).. in this columns first zero is not get it..
so i went to change the column in cells format of text..
how to create in Vb.net code.. already i have fell excel sheet this method...
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim columnrange = oSheet.Columns
Dim therange = oSheet.UsedRange
' Dim wb As Microsoft.Office.Interop.Excel.Workbook
''Dim style As Microsoft.Office.Interop.Excel.Style
oXL = CreateObject("Excel.Application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
'oXL.Selection.num()
oXL.Selection.NumberFormat = "Text"
For c As Integer = 0 To dt.Columns.Count - 1
oSheet.Cells(1, c + 1).Value = dt.Columns(c).ColumnName
Next
For rCnt As Int16 = 2 To therange.Rows.Count
Dim rowArray(therange.Columns.Count) As String
For cCnt As Int16 = 1 To therange.Columns.Count
Dim Obj = CType(therange.Cells(rCnt, cCnt), Excel.Range)
Dim celltext As String
celltext = Obj.Value.ToString
rowArray((cCnt - 1)) = celltext
Next
Next
For r As Integer = 0 To dt.Rows.Count - 1
For c As Integer = 0 To dt.Columns.Count - 1
oSheet.Cells(r + 2, c + 1).Value = dt.Rows(r)(c)
oSheet.Cells(r + 2, c + 1).numberformat = "0"
Next
Next
'With oWB
' .Cells(seriesName.GetUpperBound(0) + 7, 3).numberformat = "#.00"
' .Cells(seriesName.GetUpperBound(0) + 7, 5).numberformat = "0"
'End With
'With oSheet.Range("A1", "ZZ1")
' .Font.Bold = True
' .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
' .HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
' .EntireColumn.AutoFit()
' .EntireRow.AutoFit()
'End With
Dim FirstRow As Long
Dim SecentRow As Long
Dim ThirdRow As Long
With oSheet.Range("A1", "BD1")
FirstRow = 1
SecentRow = 2
ThirdRow = 3
.Rows(0 + 1).EntireRow.Insert()
.Rows(0 + 1).EntireRow.Insert()
.Rows(0 + 1).EntireRow.Insert()
.Font.Bold = True
.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
.EntireColumn.AutoFit()
.EntireRow.AutoFit()
'.EntireRow.TextToColumns()
.Offset.Justify()
.Offset.BorderAround()
.Offset.WrapText = True
.Offset.Select()
End With
But right now idon't get the ans...
to pls help Me ...
Prefix the value in the cells you want to treat as text with a leading single quote '. This forces Excel to treat the cell as text, and the single quote will not be visible in the sheet.
oSheet.Range("A1", "BD1").NumberFormat = "#"
this will do the trick.