Click here to Skip to main content
15,919,340 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a question,

With this code i write some text to a excel sheet en print it out.

Works fine

But i want to save the file , and ad some more data to the sheet in the next empty row

Now it is going to row 1 cel a en b

Next time is has to go to row 2 a en b and so on

The next empty row.


VB
Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop

Public Class Form1
    Private Worksheets As Object

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        InitializeComponent()
        Dim AppExcel As Object
        Dim workBook As Object
        AppExcel = CreateObject("Excel.Application")


        workBook = AppExcel.Workbooks.Open(My.Application.Info.DirectoryPath & "\test.xls")
        AppExcel.Visible = False
        Worksheets = workBook.worksheets

        AppExcel.Visible = True


        Worksheets("blad1").Cells(1, 1).value = Form2.TextBox1.Text
         Worksheets("blad1").Cells(1, 2).value = Form2.TextBox2.Text
        
     

        Worksheets("blad1").PrintOut()
       



        Dim oXL As Application
        Dim oWB As Excel.Workbook
        Dim oSheet As Excel.Workbook
        Dim oRng As Excel.Range


        workBook.Saved = False


        ' Make sure that you release object references.
        oRng = Nothing
        oSheet = Nothing
        oWB = Nothing
        AppExcel.Quit()
        oXL = Nothing

        GC.Collect()
       
        Me.Close()

    End Sub
End Class
Posted
Updated 22-Aug-11 8:44am
v2

1 solution

VBA Excel:
VB
Function FirstEmptyRow(oWsh As Worksheet, sCol As String, startRow As Long) As Long
    FirstEmptyRow = oWsh.Range(sCol & startRow).End(xlDown).Row
End Function

You can translate it to VB.NET:
VB
Function FirstEmptyRow(oWsh As Object, sCol As String, startRow As Long) As Long
    Return oWsh.Range(sCol & startRow.ToString).End(-4121).Row
End Function


Usage:
VB
Sub Adsasada()
MsgBox FirstEmptyRow(oWb.Worksheets("blad1"), "A", 1)
End Sub

It works fine, if you got some data... but if you don't, function returns last row, so... you need something like this:
VB
Function FirstEmptyRow(oWsh As Object, sCol As String) As Long
    Return oWsh.Range(sCol & oWsh.Rows.Count).End(-4162).Row +1
End Function

No matter of rows count in a worksheet (MS97-2003 -> 65536 rows, 2007-2010 - much more ;)), function will return proper value
 
Share this answer
 
v2
Comments
BASSIES 31-Aug-11 4:55am    
Thanks ,

But i don't know very much about Function's.

How do i put this in my code ? and where.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900