Results 1 to 30 of 30

Thread: [RESOLVED] Writing to a new line in Excel

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Resolved [RESOLVED] Writing to a new line in Excel

    Hey everyone, I know this has been done a million times before, but I cant't get the thing to work.. I need to write to a new line in excel every time, so I guess it needs to read the last line then add text on the new one?

    Code:
     Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
            Dim excel_app As New Excel.Application()
            Dim oExcel As Object
            Dim oBook As Object
            Dim oSheet As Object
            excel_app.Visible = False
    
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Open(My.Computer.FileSystem.SpecialDirectories.Desktop + "\Repairs.xlsx")
            oSheet = oBook.worksheets(1)
    
            oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row
    '''TESTING AREA'''
            If CheckBox1.Checked = True Then
                oSheet.Cells(2, 1) = "Road Legal"
            End If
            If CheckBox2.Checked = True Then
                oSheet.Cells(2, 1) = "Off-Road Only"
            End If
    I know this wont work, I don't know what to reference when
    Code:
    oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row
    finds the last row

    Thanks
    VS 2017 - Need as much help as you can give (write it all for me!)

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel


  3. #3

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    That selects a defined range? Mine needs to scan all rows?
    VS 2017 - Need as much help as you can give (write it all for me!)

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    Try:

    Code:
    Range("A" & CStr(Range("A1").End(xlDown).Row + 1)).Select

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    Try:

    Code:
    Range("A" & CStr(Range("A1").End(xlDown).Row + 1)).Select
    Name:  Capture.PNG
Views: 1164
Size:  5.4 KB
    VS 2017 - Need as much help as you can give (write it all for me!)

  6. #6
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    It's not System.Data.Range. Try oSheet.Range.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    It's not System.Data.Range. Try oSheet.Range.
    Thanks, silly mistake for me, but xldown isnt declared?

    Guessing thats oSheet. too (Opps)
    Last edited by callumwk; Nov 2nd, 2015 at 02:54 PM. Reason: Guessing thats oSheet. too (Opps)
    VS 2017 - Need as much help as you can give (write it all for me!)

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    It's not System.Data.Range. Try oSheet.Range.
    Name:  Capture.jpg
Views: 1132
Size:  15.8 KB

    Next Problem! haha
    VS 2017 - Need as much help as you can give (write it all for me!)

  9. #9
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    I think it's Excel.xlDown
    Not sure, i tested it in VBA, hence the need to fully declare some of the functions and constants

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    I think it's Excel.xlDown
    Not sure, i tested it in VBA, hence the need to fully declare some of the functions and constants
    excel.xldown isnt a member of Microsoft.Office.Interop.Excel
    VS 2017 - Need as much help as you can give (write it all for me!)

  11. #11
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    Excel.XLDirection.xlDown

    You can google constants to find which excel class they're in...

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    Excel.XLDirection.xlDown

    You can google constants to find which excel class they're in...
    Oh Yeah... Google
    VS 2017 - Need as much help as you can give (write it all for me!)

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    Excel.XLDirection.xlDown

    You can google constants to find which excel class they're in...
    I am still getting an unhanded error...
    Name:  Capture.jpg
Views: 1085
Size:  10.3 KB
    Last edited by callumwk; Nov 2nd, 2015 at 03:08 PM. Reason: Fixing image placement
    VS 2017 - Need as much help as you can give (write it all for me!)

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    I don't see a problem, or know how to proceed with that.
    The example i gave you worked in excel 2007 vba, so it is almost definitely a conversion error.
    I'll test it in vb. Might be a few minutes...

  15. #15
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Writing to a new line in Excel

    Imports excel = Microsoft.Office.Interop.Excel
    ...
    ...
    oSheet.Range("A" & CStr(oSheet.Range("A1").End(excel.XlDirection.xlDown).Row + 1)).Select()

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by .paul. View Post
    Imports excel = Microsoft.Office.Interop.Excel
    ...
    ...
    oSheet.Range("A" & CStr(oSheet.Range("A1").End(excel.XlDirection.xlDown).Row + 1)).Select()
    Thanks, but still receiving the same error
    VS 2017 - Need as much help as you can give (write it all for me!)

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by callumwk View Post
    Thanks, but still receiving the same error
    Bump
    VS 2017 - Need as much help as you can give (write it all for me!)

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by callumwk View Post
    Thanks, but still receiving the same error
    something to do with VB not having the right permissions?
    VS 2017 - Need as much help as you can give (write it all for me!)

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel - Please Help

    Updated Code:

    Code:
            'Start Excel'
    
            Dim oXLApp As Excel.Application
            Dim oXLBook As Excel.Workbook
            Dim oXLSheet As Excel.Worksheet
            oXLApp = New Excel.Application
    
            'Open Exsisting Excel File'
    
            oXLBook = oXLApp.Workbooks.Open(My.Computer.FileSystem.SpecialDirectories.Desktop + "\Repairs.xlsx")
            oXLSheet = oXLBook.Worksheets(1)
    
            'Find Last Row'
    
            oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    
            'Edit Cells'
    
            If CheckBox1.Checked = True Then
                oXLSheet.row = "Road Legal"
            End If
            If CheckBox2.Checked = True Then
                oXLSheet.Cells(2, 1) = "Off-Road Only"
            End If
    
    
            'End Edit Cells'
    
            'Start Close Excel Procedure'
    
            oXLBook.Close(True)
            oXLSheet = Nothing
            oXLBook = Nothing
            oXLApp = Nothing
    
            releaseObject(oXLApp)
            releaseObject(oXLBook)
            GC.Collect()
            Threading.Thread.Sleep(1000)
    
            Dim xlp() As Process = Process.GetProcessesByName("EXCEL")
            For Each Process As Process In xlp
                Process.Kill()
                If Process.GetProcessesByName("EXCEL").Count = 0 Then
                    Exit For
                End If
            Next
    
            'Excel Closed'
    
            'Close Form'
    
            Me.Close()
    
        End Sub
    I know the closing of excel is unnecessary and crude but for now it doesn't matter. I get the same error every time.

    Name:  Capture.jpg
Views: 1046
Size:  18.2 KB

    The error is "An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in J&C Motors System 7.exe

    Additional information: Exception from HRESULT: 0x800A03EC"

    I don't like starting new threads all the time, but it seams when a thread gets beyond a day no one reply's :/ any help is greatly appreciated!!
    VS 2017 - Need as much help as you can give (write it all for me!)

  20. #20
    PowerPoster
    Join Date
    Oct 2008
    Location
    Midwest Region, United States
    Posts
    3,574

    Re: Writing to a new line in Excel

    Where do you get the error? I can run it successfully through the following line:

    Code:
    oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()

  21. #21
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: Writing to a new line in Excel

    Try a little test:

    Change:
    Code:
    'Find Last Row'
    
    oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    to:
    Code:
    'Find Last Row'
    
    Dim maxRow As Int32  = oXLSheet.Rows.Count
    Dim nextRow As Int32 = oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1
    If nextRow > maxRow Then Stop
    
    oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    and let us know what happens.

  22. #22
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Writing to a new line in Excel

    I have working examples here where you can run the code and see results. Granted there is a lot going on but the solution is in short what Paul is pointing too

    Here is one sample
    Code:
    Option Strict On
    Option Infer On
    
    Imports Excel = Microsoft.Office.Interop.Excel
    Imports Microsoft.Office
    Imports System.Runtime.InteropServices
    Module Demo
        ''' <summary>
        ''' Writes one value to Column specificed, last rows +1
        ''' </summary>
        ''' <param name="FileName"></param>
        ''' <param name="SheetName"></param>
        ''' <param name="Column"></param>
        ''' <param name="Value"></param>
        ''' <remarks></remarks>
        Public Sub WriteToCell(ByVal FileName As String, ByVal SheetName As String, ByVal Column As String, ByVal Value As String)
            Dim LastRowCount As Integer = 1
    
            Dim xlApp As Excel.Application = Nothing
            Dim xlWorkBooks As Excel.Workbooks = Nothing
            Dim xlWorkBook As Excel.Workbook = Nothing
            Dim xlWorkSheet As Excel.Worksheet = Nothing
            Dim xlWorkSheets As Excel.Sheets = Nothing
    
            xlApp = New Excel.Application
            xlApp.DisplayAlerts = False
            xlWorkBooks = xlApp.Workbooks
            xlWorkBook = xlWorkBooks.Open(FileName)
    
            xlApp.Visible = False
    
            xlWorkSheets = xlWorkBook.Sheets
    
            For x As Integer = 1 To xlWorkSheets.Count
    
                xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
    
                If xlWorkSheet.Name = SheetName Then
    
                    Dim xlCells As Excel.Range = xlWorkSheet.Cells()
                    Dim xlTempRange1 As Excel.Range = xlCells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell)
                    Dim xlTempRange2 = xlWorkSheet.Rows
    
    
                    Dim xlTempRange3 = xlWorkSheet.Range(Column.ToUpper & xlTempRange2.Count)
                    Dim xlTempRange4 = xlTempRange3.End(Excel.XlDirection.xlUp)
    
                    LastRowCount = xlTempRange4.Row + 1
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlCells)
                    xlCells = Nothing
    
                    xlCells = xlWorkSheet.Range(Column & LastRowCount)
                    xlCells.Value = Value
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlTempRange4)
                    xlTempRange4 = Nothing
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlTempRange3)
                    xlTempRange3 = Nothing
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlTempRange2)
                    xlTempRange2 = Nothing
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlTempRange1)
                    xlTempRange1 = Nothing
    
                    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlCells)
                    xlCells = Nothing
    
                End If
    
            Next
    
    
            ' Common reason for failure, someone has the file open and we get it in read-only 
            ' mode
            Try
                xlWorkSheet.SaveAs(FileName)
            Catch ex As Exception
                MessageBox.Show("Failed to save data" & Environment.NewLine & ex.Message)
            End Try
    
            Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
            xlWorkSheet = Nothing
    
            xlWorkBook.Close()
            xlApp.UserControl = True
            xlApp.Quit()
    
            ReleaseComObject(xlWorkSheets)
            ReleaseComObject(xlWorkSheet)
            ReleaseComObject(xlWorkBook)
            ReleaseComObject(xlWorkBooks)
            ReleaseComObject(xlApp)
        End Sub
        Private Sub ReleaseComObject(ByVal obj As Object)
            Try
                If obj IsNot Nothing Then
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                    obj = Nothing
                End If
            Catch ex As Exception
                obj = Nothing
            End Try
        End Sub
    End Module

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by TnTinMN View Post
    Try a little test:

    Change:
    Code:
    'Find Last Row'
    
    oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    to:
    Code:
    'Find Last Row'
    
    Dim maxRow As Int32  = oXLSheet.Rows.Count
    Dim nextRow As Int32 = oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1
    If nextRow > maxRow Then Stop
    
    oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    and let us know what happens.
    It stopped... then got the error on continue.
    VS 2017 - Need as much help as you can give (write it all for me!)

  24. #24
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: Writing to a new line in Excel

    Quote Originally Posted by callumwk View Post
    It stopped... then got the error on continue.
    As I suspected it would.
    That means that there is no cell filled below "A1". Now why is that the case? Either you are referencing the wrong worksheet, or your data in not what you think it is.
    This code is assigning the Worksheet on blind faith that the one you want is the first Worksheet in the WorkBook.
    Code:
    oSheet = oBook.worksheets(1)
    You could also specify the WorkSheet name instead of and index.
    Code:
    oSheet = oBook.worksheets("NameOfWorkSheet")
    Open the Workbook in Excel and find out what the first Worksheet looks like.

  25. #25

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by TnTinMN View Post
    As I suspected it would.
    That means that there is no cell filled below "A1". Now why is that the case? Either you are referencing the wrong worksheet, or your data in not what you think it is.
    This code is assigning the Worksheet on blind faith that the one you want is the first Worksheet in the WorkBook.
    Code:
    oSheet = oBook.worksheets(1)
    You could also specify the WorkSheet name instead of and index.
    Code:
    oSheet = oBook.worksheets("NameOfWorkSheet")
    Open the Workbook in Excel and find out what the first Worksheet looks like.
    Your Joking! ((( I have a line of text running in the first row, the rest are empty. Add some text in tow two, it works... I'm sorry for my stupidity.
    VS 2017 - Need as much help as you can give (write it all for me!)

  26. #26

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by TnTinMN View Post
    As I suspected it would.
    That means that there is no cell filled below "A1". Now why is that the case? Either you are referencing the wrong worksheet, or your data in not what you think it is.
    This code is assigning the Worksheet on blind faith that the one you want is the first Worksheet in the WorkBook.
    Code:
    oSheet = oBook.worksheets(1)
    You could also specify the WorkSheet name instead of and index.
    Code:
    oSheet = oBook.worksheets("NameOfWorkSheet")
    Open the Workbook in Excel and find out what the first Worksheet looks like.
    Name:  Capture.PNG
Views: 902
Size:  2.7 KB

    Just quickly, instead of
    Code:
     oXLSheet.row
    what should it be? to write into the next clear row that the previous code worked
    VS 2017 - Need as much help as you can give (write it all for me!)

  27. #27
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: Writing to a new line in Excel

    I'm glad you got that resolved. Now you know that you need to do some error checking when working with user prepared data files.

    Assuming you left that test code in,

    Code:
    oXLSheet.Cells(nextRow, 1).value = something
    Also, remove the "Stop" statement and flush out some error handling to put in the if statement. Have fun.

  28. #28

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    Quote Originally Posted by TnTinMN View Post
    I'm glad you got that resolved. Now you know that you need to do some error checking when working with user prepared data files.

    Assuming you left that test code in,

    Code:
    oXLSheet.Cells(nextRow, 1).value = something
    Also, remove the "Stop" statement and flush out some error handling to put in the if statement. Have fun.
    Yeah.. stupid me really :L

    I have:
    Code:
            Dim maxRow As Int32 = oXLSheet.Rows.Count
            Dim nextRow As Int32 = oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1
    
    
    
            oXLSheet.Range("A" & CStr(oXLSheet.Range("A1").End(Excel.XlDirection.xlDown).Row + 1)).Select()
    But what do I reference in this bit of code to start editing the next empty row, then a custom coloum. Ill try and Pseudocode it.

    Code:
     
      If CheckBox1.Checked = True Then
      next clear row + column 2 . text = " I know what Pseudocode means (go me) "
    VS 2017 - Need as much help as you can give (write it all for me!)

  29. #29
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: Writing to a new line in Excel

    Do not use the "Range.Select" command. It is not needed and just slows down your code. That is something the Excel Macro recorder inserts as it has no choice because it does not know the ultimate goal. Compute a row and column and use the Worksheet.Cells(row,column) to address the needed range. Think of the Worksheet as 2D array that you are interacting with.

    When in doubt about a command, refer to the Excel Object Model Reference.

  30. #30

    Thread Starter
    Lively Member
    Join Date
    Oct 2013
    Location
    United Kingdom
    Posts
    123

    Re: Writing to a new line in Excel

    The Solution

    Code:
     'Start Excel'
            Dim oExcel As Object
            Dim oBook As Object
            Dim oSheet As Object
            Dim writeRow As Long
    
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Open(My.Computer.FileSystem.SpecialDirectories.Desktop + "\Repairs.xlsx")
    
            oSheet = oBook.worksheets(1)
            writeRow = oSheet.cells(oSheet.rows.count, 1).end(XlDirection.xlUp).row + 1
    
            'Edit Cells'
    
            If CheckBox1.Checked = True Then
                oSheet.range("a" & writeRow).value = "Road Legal"
            End If
    
            If CheckBox2.Checked = True Then
                oSheet.range("a" & writeRow).value = "Off-Road Only"
            End If
    VS 2017 - Need as much help as you can give (write it all for me!)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width