View Single Post
 
Old 01-25-2012, 02:46 AM
Colin Legg's Avatar
Colin Legg Colin Legg is offline Windows 7 32bit Office 2010 32bit
Expert
 
Join Date: Jan 2011
Location: UK
Posts: 369
Colin Legg will become famous soon enough
Default

I think bosve73 finds there is a problem if someone starts inserting columns in the sheet though. Ideally this wouldn't happen and some sort of structural protection would be enforced, but using named ranges is a good safeguard. You could actually have 3 named ranges, one for each of the "Risk", "Problem" and "Status" columns.

Then your code would be something like this (I've broken it out into logical steps):

Code:
Public Sub Save_Click()
    Dim lNextRow As Long
    Dim wksDb As Worksheet
    
    Dim rngRisk As Range
    Dim rngProblem As Range
    Dim rngStatus As Range
    
    Set wksDb = Worksheets("Databas")
    
    Set rngRisk = wksDb.Range("Risk")
    Set rngProblem = wksDb.Range("Problem")
    Set rngStatus = wksDb.Range("Status")
    
    ' The statement simulates activating the last cell in the "risk" column, pressing End,
    ' pressing Up Arrow, and then moving down one row. If you do that manually,
    ' the cell pointer will be in the next empty cell in the "risk" column  — even if the data
    ' area doesn’t begin in row 1 and contains blank rows.
    lNextRow = wksDb.Cells(wksDb.Rows.Count, rngRisk.Column).End(xlUp).Offset(1, 0).Row
    
    wksDb.Cells(lNextRow, rngRisk.Column) = Me.cboRisk.Value
    wksDb.Cells(lNextRow, rngProblem.Column) = Me.txtProblem.Value
    wksDb.Cells(lNextRow, rngStatus.Column) = Me.cboStatus.Value
End Sub
Reply With Quote