Skip certain cells when adding values to DGV column - vb.net

I can not get this to work. I am trying to populate column 2 with values from txt file and to skip cells that has no value in column 1 but without skipping data from text file.
This is what I get :
And code that I'm using :
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i).Cells(1).Value Is Nothing Then
'MsgBox(DataGridView1.Rows(i).Index)
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.WhiteSmoke
Else
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i).Cells(2).Value = LBS001(0)
Next
End If
Next
In code above line If DataGridView1.Rows(i).Cells(1).Value Is Nothing is not working. When that line is replaced with this one If DataGridView1.Rows(i).Cells(1).Value = "", I get this :
Here A201A is missing and for every empty row in column1 1 result is going to be skipped.
How to populate column 2 with data from txt file so that only rows are skipped not results.
EDIT :
I've tried something else and it works for the first empty cell in column 2, but when it comes to a second...it skips one data from array and then continues normally until reaches another empty cell. Example : A201A...A224A (everything OK)...blank cell(skipped)...A205 in OK but in 206 cell it puts A207A.
Now, this code below works too, thanks to Steve.
Dim Dat2() As String = Split(start1(0), Environment.NewLine)
Dim Dat2A() As String = Split(Dat2(0), ";")
Dim Dat2B() As String = Split(Dat2(1), ";")
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
Dim a As Integer = 0
For x As Integer = 0 To DataGridView1.Rows.Count - 2
If DataGridView1.Rows(x).Cells(1).Value <> "" Then
DataGridView1.Rows(x).Cells(2).Value = Dat2(a)
a += 1
Else
DataGridView1.Rows(x).Cells(2).Value = ""
End If
End If
Next
EDIT 2 :
Thanks to Steve...I've changed code a bit and it works. Only problem is I am missing two lines in lineCount I think because of every DGV row that is skipped.
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lineCount = System.IO.File.ReadAllLines(fileName).Length
Dim lines() = System.IO.File.ReadAllLines(fileName)
MsgBox(lineCount)
Dim i2 As Integer = 0
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i2).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i).Cells(1).Value <> "" Then
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i).Cells(2).Value = LBS001(0)
Next
i2 += 1
Else
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.WhiteSmoke
End If
Next

What you are doing now is using i to read the line and i to write to your grid. What you need is another variable like i2 that you increment manually when you set the value in a grid, or need to skip a line in the grid.
Dim i2 as Int32 = 0
For i As Integer = 0 To lineCount
Dim RM001 As String = lines(i).Replace(".", "")
Dim LBS001() As String = RM001.Split(New String() {";"}, StringSplitOptions.None)
On Error Resume Next
Dim Val = LBS001(1)
Dim Val2 = LBS001(2)
If DataGridView1.Rows(i2).Cells(1).Value Is Nothing Then
'MsgBox(DataGridView1.Rows(i2).Index)
DataGridView1.Rows(i2).DefaultCellStyle.BackColor = Color.WhiteSmoke
Else
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(i2).Cells(2).Value = LBS001(0)
Next
i2 += 1
End If
Next
EDIT: After further review and edits by the OP, this is a better answer:
Dim fileName = "X:\2013\NKT13\FI-ZL\BU.rev"
Dim lines() = System.IO.File.ReadAllLines(fileName)
Dim lineCount = lines.Length
Dim a As Integer = 0
For x As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(x).Cells(1).Value <> "" Then
DataGridView1.Rows(x).Cells(2).Value = lines(a)
a += 1
Else
DataGridView1.Rows(x).Cells(2).Value = ""
End If
Next

Related

VBA split string sentences with multiple values

My Excel raw data looks something like this:
;123456p,Roses and butterflies;;124456h,Violets are blue;
;123456d,Hello world;
Expected output:
Roses and butterflies
Violets are blue
Hello world
Trying to split the text sentences out only, for rows with multiple sentences I would need them in
separate rows, is this at all possible? Below is what I tried.
Private Sub CommandButton1_click()
Dim splitstring As String
Dim myarray() As String
splitstring = Worksheets("raw").Cells(1, 1).Value
myarray = Split(splitstring, ";")
For i = 0 To URound(myarray)
Next
End Sub
Sub raw()
End Sub
With Regular Expressions, you can populate Column B with the desired results ae below
Option Explicit
Private Sub CommandButton1_click()
Dim wSh As Worksheet
Dim rngStr As String, rngStrArr() As String, i As Long
Set wSh = Worksheets("raw")
Dim regEx As Object, mc As Object
Set regEx = CreateObject("vbscript.regexp")
regEx.Global = True
regEx.IgnoreCase = True
rngStr = Join(Application.Transpose(Application.Index(( _
wSh.Range("A1:A" & wSh.Cells(wSh.Rows.Count, 1).End(xlUp).Row)), 0, 1)))
regEx.Pattern = ",([^;]+);"
Set mc = regEx.Execute(rngStr)
rngStr = ""
For i = 0 To mc.Count - 1
rngStr = rngStr & mc(i)
Next i
rngStr = Replace(rngStr, ",", "")
rngStrArr = Split(rngStr, ";")
wSh.Range("B1").Resize(UBound(rngStrArr), 1).Value = Application.Transpose(rngStrArr)
End Sub
Try this:
Private sub SplitString()
Dim splitstring As String
Dim myarray() As String
splitstring = Cells(1, 1).Value
myarray = Split(splitstring, ",")
For i = 1 To UBound(myarray)
MsgBox (myarray(i))
Next
End Sub

vb.net Export Datagridview to excel template

I want to export my datagridview rows to a existing excel template with headers that will start from cell A10:AA10.
This is the template:
I've tried this
Public Sub exportToexcel()
Dim default_location As String = "D:\Book1.xlsx"
Dim dset As New DataSet
dset.Tables.Add()
For i As Integer = 0 To dgvReports.ColumnCount - 1
dset.Tables(0).Columns.Add(dgvReports.Columns(i).HeaderText)
Next
add rows to the table
Dim dr1 As DataRow
For i As Integer = 0 To dgvReports.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To dgvReports.Columns.Count - 1
dr1(j) = dgvReports.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As Microsoft.Office.Interop.Excel.Application
excel = New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
excel.Visible = True
excel.UserControl = True
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("Sheet1")
excel.Range("A50:I50").EntireColumn.AutoFit()
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "Sheet1"
End With
Dim dt As System.Data.DataTable = dset.Tables(0)
' wSheet.Cells(1).value = strFileName
For Each col As DataGridViewColumn In dgvReports.Columns
wSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString
Next
For i = 0 To dgvReports.RowCount - 1
For j = 0 To dgvReports.ColumnCount - 1
wSheet.Columns.NumberFormat = "#"
wSheet.Cells(i + 2, j + 1).value = dgvReports.Rows(i).Cells(j).Value.ToString
Next j
Next i
wSheet.Columns.AutoFit()
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(default_location)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try
If System.IO.File.Exists(default_location) Then
System.IO.File.Delete(default_location)
End If
wBook.SaveAs(default_location)
excel.Workbooks.Open(default_location)
excel.Visible = True
End Sub
This only creates a new excel file. I just need to feel a existing excel file.
Replace this line:
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
that code will add a new Workbook to your newly created Excel.
This will open the file assigned to the default_location variable:
wBook = excel.Workbooks.Open(default_location)

export the listview items to excel sheet with listview header

I have this code to export the data in listview to excel sheet, but this code export data without the header of list view.
How can I edit this code to show the header of the listview?
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 1
Dim col As Integer = 1
For Each item As ListViewItem In ListView1.Items
For i As Integer = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)
End Sub
Private Sub releaseObject(ByVal obj As Object)
'Release an automation object
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You can get each column text by using this code:
Dim columns As New List(Of String)
Dim columncount As Integer = ListView1.Columns.Count - 1
For i As Integer = 0 To columncount
columns.Add(ListView1.Columns(i).Text)
Next
For Each columnname In columns
MessageBox.Show(columnname)
Next
Before you enter the loop to export your data you need to iterate the ColumnHeaderCollection in the ListView
For i = 0 To ListView1.Columns.Count - 1
sheet.Cells(1, i + 1) = ListView1.Items(i).Name
Next
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 2
Dim col As Integer = 1
'////////////////////////////////////////////////////////////////////////
Dim rowhead As Integer = 1
Dim colhead As Integer = 1
Dim columns As New List(Of String)
Dim columncount As Integer = LvCOCONFIRMATION.Columns.Count - 1
For i As Integer = 0 To columncount
sheet.Cells(rowhead, colhead) = LvCOCONFIRMATION.Columns(i).Text
colhead = colhead + 1
Next
'////////////////////////////////////////////////////////////////////////
For Each item As ListViewItem In LvCOCONFIRMATION.Items
For i As Integer = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)

Exporting Data To Multiple Excel Sheets

I'm Using following code to export my listview to Excelsheet but the problem is i have multiple listviews which i have to export in different sheets in same excel file . . . . .
Dim flnameSaveAs As String = System.IO.Path.GetFileName(Main.spath1)
'Save Files name
Dim extension As String
extension = Path.GetExtension(Main.spath1)
Dim file As String = System.IO.Path.GetFileName(Main.spath1)
Dim FinenameA As String = System.IO.Path.GetDirectoryName(Main.spath1)
Dim savnames As String
savnames = file.Substring(0, Len(file) - Len(extension))
Dim ExportSheet As String
ExportSheet = deskPath + "\Cel_ID_TimeLine.txt"
Dim lvi As ListViewItem
Dim sb As New System.Text.StringBuilder
Dim sbhd As New System.Text.StringBuilder
Dim columns As Integer = lvCidTimeLine.Columns.Count
For ixhd As Integer = 0 To lvCidTimeLine.Columns.Count - 1
sbhd.Append(lvCidTimeLine.Columns(ixhd).Text)
sbhd.Append(vbTab)
Next
sb.Append(vbCrLf)
For Each lvi In lvCidTimeLine.Items
For ix As Integer = 0 To lvi.SubItems.Count - 1
sb.Append(lvi.SubItems(ix).Text)
If ix < lvi.SubItems.Count - 1 Then
sb.Append(vbTab)
Else
sb.Append(vbCrLf)
End If
Next
Next
Dim sw As New StreamWriter(ExportSheet)
sw.Write(sbhd.ToString)
sw.Write(sb.ToString)
sw.Close()
Dim oExcel As Excel.Application
' Create the spreadsheet
oExcel = CreateObject("Excel.Application")
oExcel.Workbooks.OpenText(ExportSheet, , , , -4142, , True)
oExcel.Cells.EntireColumn.AutoFit()
oExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + ".xls", -4143)
oExcel.Quit()
oExcel = Nothing
So do you have any idea how to add another sheet and export another listview to it ??
Try This Code Instead
Try
Dim objExcel As New Excel.Application
Dim bkWorkBook As Excel.Workbook
Dim shWorkSheet As Excel.Worksheet
Dim shWorkSheet1 As Excel.Worksheet
Dim i As Integer
Dim j As Integer
objExcel = New Excel.Application
bkWorkBook = objExcel.Workbooks.Add
shWorkSheet = CType(bkWorkBook.ActiveSheet, Excel.Worksheet)
For i = 0 To lv1.Columns.Count - 1
shWorkSheet.Cells(1, i + 1) = lv1.Columns(i).Text
Next
For i = 0 To lv1.Items.Count - 1
For j = 0 To lv1.Items(i).SubItems.Count - 1
shWorkSheet.Cells(i + 2, j + 1) = lv1.Items(i).SubItems(j).Text
Next
Next
shWorkSheet1 = bkWorkBook.Worksheets.Add(, shWorkSheet, , )
For i = 0 To lv2.Columns.Count - 1
shWorkSheet1.Cells(1, i + 1) = lv2.Columns(i).Text
Next
For i = 0 To lv2.Items.Count - 1
For j = 0 To lv2.Items(i).SubItems.Count - 1
shWorkSheet1.Cells(i + 2, j + 1) = lv2.Items(i).SubItems(j).Text
Next
Next
objExcel.Visible = False
objExcel.Application.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs(savpath + "\" + savnames + "_1" + ".xls", -4143)
objExcel.Quit()
objExcel = Nothing
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
You need to ADD to the sheets collection. Interop Excel Sheets

VB.Net: DAO Object won't create DBEngine

I'm using a dynamically created Access database as a temporary storage for a file being inputed. I know that everything works, as on my dev machine I can get this code to run. But on another system (Win 7) it's not working. I'm being stopped at this line...
DAOEngine = New DAO.DBEngine
When it gets here, it just throws an error...
Creating an instance of the COM component with CLSID {00000010-0000-0010-8000-00AA006D2EA4} from the IClassFactory failed due to the following error: 80040112.
I have searched for the error, and I can't make sense of what it's telling me other then I'm using an old way of creating databases. And right now, I was hoping for a quick fix rather then rewriting the way my storage is working.
Again, I know my code is correct because my Dev machine compiles and runs this code just fine. I'll post the entire method in case there's something else I'm missing.
Private Sub ProcessFile(ByVal Exportname As String, ByVal ExportFile As String, ByVal ImportFile As String)
' Aperture variables
Dim Table As Object 'OETable
Dim Fields As Object 'OEFields
' DAO database variables
Dim DAOEngine As DAO.DBEngine
Dim rst As DAO.Recordset
Dim ws As DAO.Workspace
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim fld As DAO.Field
' Integer vars
Dim fieldcount As Integer
Dim I As Integer
Dim j As Integer
' Boolean Variables
Dim CalcTotals As Boolean = False
' String Array Variables
Dim headers() As String = Nothing
' String Variables
Dim lvl_lookup As String
Dim outputlist As String
Dim throwaway As String = ""
Dim totalstring As String
' Array vars
Dim totals() As Object
' Use an access database to add the serial numbers
'ws = DAODBEngine_definst.Workspaces(0)
DAOEngine = New DAO.DBEngine
ws = DAOEngine.Workspaces(0)
If File.Exists(alAperture.prjPath & "\temp.mdb") Then
File.Delete(alAperture.prjPath & "\temp.mdb")
End If
db = ws.CreateDatabase(alAperture.prjPath & "\temp.mdb", DAO.LanguageConstants.dbLangGeneral)
tbl = db.CreateTableDef("legend")
If alAperture.tbls.Item(Exportname & " Table") Is Nothing Then
Table = alAperture.tbls.Item("Legend Text Table")
Else
Table = alAperture.tbls.Item(Exportname & " Table")
End If
Fields = Table.Fields
fieldcount = Fields.Count
' Create the fields
For I = 0 To fieldcount - 1
If Fields.Item(I).DataType = 2 Then
' We have a numeric field
fld = tbl.CreateField(Fields.Item(I).Name, 6)
CalcTotals = True
Else
fld = tbl.CreateField(Fields.Item(I).Name, 10, 255)
fld.AllowZeroLength = True
End If
tbl.Fields.Append(fld)
Next
' Create the table
db.TableDefs.Append(tbl)
' Open the table as a recordset
rst = db.OpenRecordset("legend", DAO.RecordsetTypeEnum.dbOpenTable)
' Open the exportfile for read
Dim streamIn As StreamReader = New StreamReader(ExportFile)
ReDim totals(fieldcount - 1)
I = 0
lvl_lookup = ""
Do
' Grab next record and redim to dimension of table, minus the series column
Dim nextRecord() As String = Split(streamIn.ReadLine, """,""")
ReDim Preserve nextRecord(fieldcount - 1)
If I = 0 Then
headers = nextRecord
I = 1
Else
' *** HEADER RECORD
If lvl_lookup = "" Then
lvl_lookup = nextRecord(0)
' Add the header record
rst.AddNew()
rst.Fields(0).Value = lvl_lookup
rst.Fields(1).Value = 0
For j = 2 To fieldcount - 1
If rst.Fields(j).Type = 10 Then
rst.Fields(j).Value = Replace(headers(j - 1), """", "")
Else
rst.Fields(j).Value = 0
End If
Next
rst.Update()
End If
' *** RECORDS
If nextRecord(0) = lvl_lookup Then
' addrecords
addrecord(totals, nextRecord, rst, fieldcount, I)
Else
' add total row
' padlines
If CalcTotals Then
rst.AddNew()
rst.Fields(0).Value = lvl_lookup
rst.Fields(1).Value = I
totalstring = "Total:"
For j = 2 To fieldcount - 2
If rst.Fields(j).Type = 6 Then
If IsNothing(totals(j)) Then
rst.Fields(j).Value = 0
Else
rst.Fields(j).Value = totals(j)
End If
Else
rst.Fields(j).Value = totalstring
totalstring = ""
End If
Next
rst.Fields(9).Value = 0
rst.Update()
I = I + 1
End If
'padlines
While I <= 80
rst.AddNew()
rst.Fields(0).Value = lvl_lookup
rst.Fields(1).Value = I
rst.Update()
I = I + 1
End While
I = 1
lvl_lookup = nextRecord(0)
ReDim totals(fieldcount - 2)
' add record
addrecord(totals, nextRecord, rst, fieldcount, I)
End If
If streamIn.EndOfStream Then
' add total row
' padlines
If CalcTotals Then
rst.AddNew()
rst.Fields(0).Value = lvl_lookup
rst.Fields(1).Value = I
totalstring = "Total:"
For j = 2 To fieldcount - 2
If rst.Fields(j).Type = 6 Then
If IsNothing(totals(j)) Then
rst.Fields(j).Value = 0
Else
rst.Fields(j).Value = totals(j)
End If
Else
rst.Fields(j).Value = totalstring
totalstring = ""
End If
Next
rst.Fields(9).Value = 0
rst.Update()
I = I + 1
End If
'padlines
While I <= 80
rst.AddNew()
rst.Fields(0).Value = lvl_lookup
rst.Fields(1).Value = I
rst.Update()
I = I + 1
End While
End If
End If
Loop Until streamIn.EndOfStream
streamIn.Close()
' ok lets write the import file
Dim streamOut As StreamWriter = New StreamWriter(ImportFile)
rst.MoveFirst()
Do Until rst.EOF
outputlist = Chr(34) & rst.Fields(0).Value & Chr(34) & "," & Chr(34) & VB6.Format(rst.Fields(1).Value, "00") & Chr(34)
For j = 2 To fieldcount - 1
outputlist = outputlist & "," & Chr(34) & rst.Fields(j).Value & Chr(34)
Next
streamOut.WriteLine(outputlist)
rst.MoveNext()
Loop
streamOut.Close()
rst.Close()
db.Close()
ws.Close()
rst = Nothing
db = Nothing
ws = Nothing
fld = Nothing
tbl = Nothing
Table = Nothing
Fields = Nothing
End Sub
Are you using Microsoft DAO 3.6? Using 'Microsoft DAO 2.5/3.51 Compatibility Library' is very old. DAO 3.5 is the version which comes with Access 97.
Later I should've done a search on the GUID in the error message. Yes, that GUID is for DAO 3.5 which is very old and comes with Access 97 and Visual Basic 6. Use DAO 3.6/Jet 4.0 which comes with Weindows 2000 and newer OSs.
From PRB: CLSID {00000010-0000-0010-8000-00AA006D2EA4} Not Found When You Run an Application "The {00000010-0000-0010-8000-00AA006D2EA4} CLSID is associated with DAO350.dll."