Excel cell Format Changes in text - vb.net

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.

Related

extract column range from formula in excel using macro

Sub AddNameNewSheet1()
Dim wsToCopy As Worksheet, wsNew As Worksheet
Dim Newname As String
Newname = InputBox("Number for new worksheet?")
Set wsToCopy = ThisWorkbook.Sheets("Sheet1")
Set wsNew = ThisWorkbook.Sheets.Add
If Newname <> "" Then
wsNew.Name = Newname
End If
wsToCopy.Cells.Copy wsNew.Cells
Dim cell As Range
Dim bIsNumeric As Boolean
Dim testFormula As String
bIsNumeric = False
For Each cell In wsNew.Range("A1:M40")
If cell.HasFormula() = True Then
If bIsNumeric Then
If testFormula = CStr(cell.Formula) Then
cell.Value = "<"
Else
testFormula = cell.Formula
cell.Value = "F"
End If
Else
testFormula = cell.Formula
cell.Value = "F"
End If
bIsNumeric = True
ElseIf IsNumeric(cell) = True Then
bIsNumeric = False
If Len(cell) > 0 Then
cell.Value = "N"
End If
Else
bIsNumeric = False
cell.Value = "L"
End If
Next cell
End Sub
I want to extract column and row that applied in formula. For example,
if formula is =SUM(A10:F10) then I want both A10 and F10 then I remove that is there any way to find out that.
My actual purpose is finding formula without column and row value.
thanks in advance.
If you want to get A10 and F10 from the formula, you can use this, passing your range to strRange:
Sub Extract_Ranges_From_Formula()
Dim strRange As String
Dim rCell As Range
Dim cellValue As String
Dim openingParen As Integer
Dim closingParen As Integer
Dim colonParam As Integer
Dim FirstValue As String
Dim SecondValue As String
strRange = "C2:C3"
For Each rCell In Range(strRange)
cellValue = rCell.Formula
openingParen = InStr(cellValue, "(")
colonParam = InStr(cellValue, ":")
closingParen = InStr(cellValue, ")")
FirstValue = Mid(cellValue, openingParen + 1, colonParam - openingParen - 1)
SecondValue = Mid(cellValue, colonParam + 1, closingParen - colonParam - 1)
Debug.Print FirstValue
Debug.Print SecondValue
Next rCell
End Sub
It does a Debug.Print of the two returned values.

Error hresult 0x800a03ec trying to assign value to excel cell

I'm trying to export the content of a DataGridView to an excel worksheet by using the below code
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Add
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet = CType(xlBook.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)
xlSheet.Name = "MySheet"
xlApp.Visible = True
With xlSheet
For C As Integer = 0 To DGV_IntCalc.Columns.Count - 1
.Range(.Cells(1, C + 1)).Value = DGV_IntCalc.Columns(C).HeaderText
For R As Integer = 0 To DGV_IntCalc.RowCount - 1
.Range(.Cells(R + 2, C + 1)).Value = DGV_IntCalc.Rows(R).Cells(C).Value
Next
Next
End With
I get error on .Range(.Cells(1, C + 1)).Value = DGV_IntCalc.Columns(C).HeaderText
I have Option Strict On so I can't use .Cells(1, C + 1).Value = DGV_IntCalc.Columns(C).HeaderText because of the late binding
Where am I wrong?
Even if the range has only one cell, you need to insert both starting and ending cells of the range.
The solution is to change:
.Range(.Cells(1, C + 1)).Value = DGV_IntCalc.Columns(C).HeaderText
with:
.Range(.Cells(1, C + 1), .Cells(1, C + 1)).Value = DGV_IntCalc.Columns(C).HeaderText

Cell date format in excel showing datetime

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.

Sum Up all the Data in a Column and Display it Below VB.Net and Excel

Good Afternoon to all
I populate data in Datagridview from mySQL like this.
Datagridview Data
the next thing I do is that I have an Export Button and if I Click that it will Export the Data from Datagridview in Excel like this
Extracted in Excel
My Question is How can I Find the Last Data in Column "Total" and Put the Sum below that? As of now the Image shows only two rows in excel but someday it will populate, I just want to Sum up all the data in the Column "Total" and Display the Output in below the last Data. I hope you help me. :(
TYSM
by the way here is my code
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 exl As Excel.Application
Dim NewWorksheet As Microsoft.Office.Interop.Excel.Worksheet
Dim myRange As Microsoft.Office.Interop.Excel.Range
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
exl = New Excel.Application
exl.Visible = True
With ExcelSheet
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(1, column.Index + 1) = column.HeaderText
Next
For i = 1 To Me.DataGridView1.RowCount
.cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("ItemCode").Value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
.Cells(4, 13) = "Grand Total"
.Cells(4, 14).Formula = "=SUM(Sheet1!$J2:$J1048576)"
Next
Next
End With
NewWorksheet = DirectCast(ExcelBook.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)
myRange = NewWorksheet.Range("A:K")
myRange.Font.Bold = True
myRange.Font.Size = 9
myRange.Font.FontStyle = "Calibri"
ExcelSheet.Rows.Item(1).EntireColumn.AutoFit()
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End If
Excel coordinates work by (column, row)
Dim rowIndex As Integer = 1
For i = 1 To Me.DataGridView1.RowCount
.cells(1, i + 1) = Me.DataGridView1.Rows(i - 1).Cells("ItemCode").Value
rowIndex += 1
For j = 1 To DataGridView1.Columns.Count - 1
.cells(j + 1, i + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
.Cells(9, rowIndex + 1) = "Grand Total"
.Cells(10, rowIndex + 1).Formula = "=SUM(Sheet1!J2:J" & rowIndex.ToString().Trim() & ")"

Using VBA to copy data from one worksheet into another worksheet

I have a slight problem in Excel. I need to sync up the values in the curly braces {} found in column C and put them against the user id in column F. I would like this data to be copied across to a new worksheet in the same workbook. Any ideas how I could accomplish this? You don't have to provide any code but a nudge in the right direction would be great.
E.g. on the Emails sheet
becomes this on a new sheet
In case anyone needs help, this is the solution:
Sub CopyConditional()
Dim wshS As Worksheet
Dim WhichName As String
Set wshS = ActiveWorkbook.Sheets("Emails")
WhichName = "NewSheet"
Const NameCol = "C"
Const FirstRow = 1
Dim LastRow As Long
Dim SrcRow As Long
Dim TrgRow As Long
Dim wshT As Worksheet
Dim cpt As String
Dim user As String
Dim computers() As String
Dim computer As String
On Error Resume Next
Set wshT = Worksheets(WhichName)
If wshT Is Nothing Then
Set wshT = Worksheets.Add(After:=wshS)
wshT.Name = WhichName
End If
On Error GoTo 0
If wshT.Cells(1, NameCol).value = "" Then
TrgRow = 1
Else
TrgRow = wshT.Cells(wshT.Rows.Count, NameCol).End(xlUp).Row + 1
End If
LastRow = wshS.Cells(wshS.Rows.Count, NameCol).End(xlUp).Row
For SrcRow = FirstRow To LastRow
cpt = wshS.Range("C" & SrcRow).value
user = wshS.Range("F" & SrcRow).value
If InStr(cpt, ":") Then
cpt = Mid(cpt, InStr(1, cpt, ":") + 1, Len(cpt))
End If
If InStr(cpt, ";") Then
computers = Split(cpt, ";")
For i = 0 To UBound(computers)
If computers(i) <> "" Then
wshT.Range("A" & TrgRow).value = user
wshT.Range("B" & TrgRow).value = Mid(Left(computers(i), Len(computers(i)) - 1), 2)
TrgRow = TrgRow + 1
End If
Next
Else
computer = cpt
If computer <> "" Then
wshT.Range("A" & TrgRow).value = user
wshT.Range("B" & TrgRow).value = Mid(Left(computer, Len(computer) - 1), 2)
TrgRow = TrgRow + 1
End If
End If
Next SrcRow
End Sub
You didn't ask a question. Basically what you would do is
loop through the values in column F
for each value, get the value in column C
loop through all braced values in column C
let braceValue = parse column C searching for {value}
create a row in new worksheet with column F value, braceValue