looping read excel data - excel

I need to loop the read data from excel to vb.net and when I reach the last row/column "!##$%^&*()" the excel data will stop read. How can I do that?
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xRange As Excel.Range
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub cmdGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGenerate.Click
'Dim row As String
Dim empty_cell_ctr As Integer = 0 '5
Dim end_of_xlsheet As Boolean = False
Dim sRow As Integer 'start row
Dim col_end As Integer 'col W
'
'loading excel(open and read)
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open("c:\sample.xls")
xlWorkSheet = xlWorkBook.Worksheets("Timesheet")
xlApp.Visible = True
While Not end_of_xlsheet
If sRow = "'!##$%^&*()_+" Then
xRange = xRange.Cells(sRow, col_end)
end_of_xlsheet = False 'end of sheet
Continue While
End If
sRow += 1
End While
MessageBox.Show(sRow)
End Sub
End Class

You seem to be overthinking this, you can get all of the data in the spreadsheet by accessing the UsedRange property, and then load this into a 2D array variable by accessing the Value2 property of this object like so:
Dim application = New Excel.Application()
Dim workbook As Excel.Workbook = application.Workbooks.Open("C:\aaa\bbb.xlsx")
Dim worksheet As Excel.Worksheet = workbook.Sheets(1)
Dim usedRange = worksheet.UsedRange
Dim usedRangeAs2DArray As Object(,) = usedRange.Value2
workbook.Save()
workbook.Close()
application.Quit()
Marshal.ReleaseComObject(application)

You may use LIKE operator :)
'Not sure why you are trying to check Row number for set of characters...
Excel.Range range = sheet.UsedRange;
Int rows_count = range.Rows.Count;
For (int sRow = 1; sRow <= rows_count; sRow++)
If (sheet.Cells[sRow, col_end].value Like "*'!##$%^&*") Then
'-- input the data to where ever you want. It is best to store it into an array first..
xRange = sheet.Cells[i, col_end].value;
Break;
Else
sRow++;
End If
Please take a look the following reference for better understanding your options.
import data from Excel to VB.Net
read data from Excel to VB.Net

Related

Pass data from Excel sheet to a DatagridView VB VSTO

Help, I want to pass the data from sheet1 (Home) of excel, to my datagridView Content in Form1.
Sub LoadDataGridView()
Dim sSheet As Excel.Worksheet = Globals.ThisWorkbook.Sheets("Home")
Dim MyRegionSelected As Excel.Range = sSheet.Range("A1")
Dim ultFila As Long = MyRegionSelected.CurrentRegion.Rows.Count
Dim i As Long
For i = 2 To ultFila
dgvlist.Columns(0).HeaderText = "Name"
dgvlist.Columns(1).HeaderText = "Number"
dgvlist.DataSource = sSheet.Cells(i, 1).ToString
dgvlist.DataSource = sSheet.Cells(i, 2).ToString
Exit For
Next
End Sub

VBA Reaching Active Excel Workbook from Another Applicatiom

I am trying to make program to see the excel workbook that is already open, but it doesn't. Controlling with xlApp.Visible = True line creates a new excel document instead making the open one visible. Any suggestions please?
Edit: I added the rest of the code here. Using catia, I am trying to reach the open excel worksheet and make modifications on it. In this case I am trying to select A1:E5 cells one by one and clear their contents
Sub CATMain()
Dim xlApp As Excel.Application
'On Error Resume Next
Set xlApp = VBA.GetObject("", "Excel.Application")
Dim exlBook As Workbook
Set exlBook = xlApp.ActiveWorkbook
Dim exlSheet As Worksheet
Set exlSheet = xlApp.ActiveSheet
xlApp.Visible = True
Dim cell1 As Integer
Dim cell2 As Integer
Dim cell3 As Integer
Dim cell4 As Integer
Dim myRange As Range
cell1 = 1 'InputBox("Tablo Başlangıç Satırını Girin: ")
cell2 = 1 'InputBox("Tablo Başlangıç Sütununu Girin: ")
cell3 = 5 'InputBox("Tablo Bitiş Satırını Girin: ")
cell4 = 5 'InputBox("Tablo Bitiş Sütununu Girin: ")
Set myRange = exlSheet.Range(Cells(cell1, cell2), Cells(cell3, cell4))
myRange.ClearContents
End Sub

Insert text to the beginning of all cells in Excel

I have an excel file in which I have a filled column A with numeric values, I would like to add the text "dt" to the values before the numeric value. Of course, text dt would be added in the entire column where values exist. Unfortunately, something in my code does not work
Imports System
Imports System.IO
Imports Excel
Imports System.IO.FileStream
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim oExcel As New Microsoft.Office.Interop.Excel.Application
Dim oBook As Microsoft.Office.Interop.Excel.Workbook
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
oBook = oExcel.Workbooks.Open("C:\Users\PC\Desktop\1.xlsx")
oSheet = oBook.Worksheets(1)
Dim rg21 = oSheet.Columns("A:A")
rg21.Select()
rg21.NumberFormat = "#"
rg21 = "dt" & rg21
oBook.Save()
oExcel.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
oBook = Nothing
oExcel = Nothing
End Sub
End Class
I would use a loop. In Excel VBA:
Sub dural()
Dim r As Range
Set r = Columns(1).Cells.SpecialCells(2)
For Each rr In r
rr.Value = "dt" & rr.Value
Next rr
End Sub
Adapt this to VB.Net.
Simply loop through the cells with value in rg21.
This is the slow version of the loop, as far as you loop through all the 1.000.000+ cells in column A:
For Each rg In rg21.Cells
If Len(rg) Then
rg = "dt" & rg
End If
Next rg
If you want if faster it would be easier to loop only through the cells with values in the first column. Like the example from #Gary's Student:
Set r = Columns(1).Cells.SpecialCells(2)

Count lines (max) with values

I would like to count the lines that have values. I tried oSheet.Rows.Count but that doesn't work. Any idea about this?
My code is the following:
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets("Sheet")
oSheet.Range("A" & max).Value = "0000111"
oSheet.Range("B1").Value ="Name"
oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()
As said in the comments, the following code should get you the count of rows that have values based on your Range:
Dim rowCount As Integer = oSheet.UsedRange.Rows.Count()
There is however a slight issue with your code I believe. This probably won't work:
oSheet = oBook.Worksheets("Sheet")
The reason it won't, is because "Sheet" doesn't exist on a new Workbook. "Sheet1" does, so this needs to be changed to:
oSheet = oBook.Worksheets("Sheet1")
'or
oSheet = oBook.Worksheets(1) 'remember Excel collections are one based not zero based
Lastly I would look at the way you are closing Excel as oExcel.Quit() is probably leaving an instance of Excel running. Have a look at this answer which links to Siddharth Rout's bit of code:
Private Sub ReleaseObject(ByVal obj As Object)
Try
Dim intRel As Integer = 0
Do
intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Loop While intRel > 0
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You also to make sure you release in the right order and release everything. This is usually in backwards order:
ReleaseObject(oSheet)
oBook.Close()
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
However with all that said I would look at using the Microsoft.Office.Interop.Excel namespace directly rather than declaring objects:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim oExcel As New Excel.Application
Dim oWorkbooks As Excel.Workbooks = oExcel.Workbooks
Dim oWorkbook As Excel.Workbook = oWorkbooks.Add()
Dim oSheets As Excel.Sheets = CType(oWorkbook.Sheets, Excel.Sheets)
Dim oWorksheet As Excel.Worksheet = CType(oSheets(1), Excel.Worksheet)
Dim oARange As Excel.Range = oWorksheet.Range("A" & max.ToString()) 'Not sure what max is but I took the assumption it's an Integer
oARange.Value = "0000111"
Dim oBRange As Excel.Range = oWorksheet.Range("B1")
oBRange.Value = "Name"
Dim oUsedRange As Excel.Range = oWorksheet.UsedRange()
Dim rowCount As Integer = oUsedRange.Rows.Count()
oWorkbook.SaveAs("C:\Test.xlsx")
ReleaseObject(oUsedRange)
ReleaseObject(oBRange)
ReleaseObject(oARange)
ReleaseObject(oWorksheet)
ReleaseObject(oSheets)
oWorkbook.Close()
ReleaseObject(oWorkbook)
ReleaseObject(oWorkbooks)
oExcel.Quit()
ReleaseObject(oExcel)
End Sub
Private Sub ReleaseObject(ByVal obj As Object)
Try
Dim intRel As Integer = 0
Do
intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Loop While intRel > 0
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
I would also then look at turning Option Strict On:
Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.
Define a row variable as Long, then start a loop which will end when it finds a blank value in column A:
Dim lRow as Long = 1
Do until oSheet.Range("A" & lRow).Value=""
' increment the loop variable
lRow+=1
Loop
' display the result in a message block
MsgBox(lRow-1)

VBA OnSlideShowPageChange crashes when adding slide in presentation mode

I've been working with the code below and can't seem to figure out what's causing PowerPoint to crash on the last line. I've used the same block of code in other subs without issue. I suspect this may somehow be related to the onslideshowpagechange function.
The code runs through the VBA editor in PowerPoint with the following libraries.
Reference Libraries
I essentially want the code to execute when a slide change occurs in presentation mode. The part of the code that causes the crash I want to add a slide back in.
Thanks ahead of time for any help!
Public Function GetLayout( _
LayoutName As String, _
Optional ParentPresentation As Presentation = Nothing) As CustomLayout
If ParentPresentation Is Nothing Then
Set ParentPresentation = ActivePresentation
End If
Dim oLayout As CustomLayout
For Each oLayout In ParentPresentation.SlideMaster.CustomLayouts
If oLayout.Name = LayoutName Then
Set GetLayout = oLayout
Exit For
End If
Next
End Function
Sub onslideshowpagechange(ByVal SSW As SlideShowWindow)
Dim oXL As Object 'Excel.Application
Dim oWb As Object 'Excel.Workbook
Dim oSld As Slide
' Check excel workbook file status, if not open then open
Dim file_status
file_status = IsWorkBookOpen("C:\Users\schuec1\Desktop\Peoria 2017 Media\Live Analysis\Live_Analysis.xlsx")
If file_status = False Then
Set oXL = CreateObject("Excel.Application")
Set oWb = oXL.Workbooks.Open(FileName:="C:\Users\schuec1\Desktop\Peoria 2017 Media\Live Analysis\Live_Analysis")
Else
Set oXL = Excel.Application
Set oWb = ActiveWorkbook
End If
Dim sld_no As Long
Dim course As String
Dim sld_offset As Long
Dim teamno As Long
Dim lead_sld As Long
Dim cntry As String
Dim pic_flag As Shape
Dim row_space As Shape
Dim team_range As Range
Dim school As String
Dim time_car As Double
Dim diff As Double
Dim time_one As Double
Dim pos As Long
Dim dist As Double
Dim dist_one As Double
Dim pplayout As CustomLayout
sld_no = SSW.View.CurrentShowPosition
'Acceleration leaderboard
If sld_no = 1001 Then
lead_sld = sld_no
With ActivePresentation
.Slides(lead_sld).Delete
End With
Debug.Assert lead_sld <> sld_no
Set oSld = ActivePresentation.Slides.AddSlide(lead_sld, GetLayout("accel"))

Resources