Ensuring Data Populates in next available row - code in vba - excel

I am attempting to write code to enter in next available row a value of 1 when a checkbox is checked and value of 0 if unchecked.
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
Set LastRow = Sheet9.Range("a70000").End(xlUp)
LastRow.Offset(1, 2).Value = 1
End If
If CheckBox2.Value = False Then
LastRow.Offset(1, 2).Value = 0
End If
End Sub
Private Sub enterMDGfunction_Click()
Dim LastRow As Object
Set LastRow = Sheet9.Range("a70000").End(xlUp)
Unload Me
DataEntrySystemHomepage.Show
End Sub
Currently it wont enter into next available row. After one entry the datasheet stops populating. Does it have to do with my unload form code?

Set LastRow = Sheet9.Range("a70000").End(xlUp)
LastRow.Offset(1, 2).Value = 1
This enters a value one row down from LastRow, in Col C, but because you never put anything new in Col A, the next time you get LastRow it will again return the same cell in ColA as previously.
Either put something in Col A, or perform the end(xlup) from Col C
With a bit of re-work it's simpler as:
Private Sub CheckBox2_Click()
Sheet9.Range("C70000").End(xlUp).Offset(1, 0).Value = _
IIf(CheckBox2.Value, 1, 0)
End Sub

Related

Select next non empty cell in A column - Excel VBA

Trying to have a button to select next non empty/blank cell in column A, relative to current row. The code below works, but only if active cell is in column A.
Need it to work on column A, even when active cell is in another column.
Private Sub CommandButton3_Click() 'Next step button - selects next step in A column
Dim n As Long
n = Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row
If ActiveCell.Row = n Then MsgBox "Last one, no more instructions.": Exit Sub
If ActiveCell.Offset(1, 0) = "" Then
ActiveCell.End(xlDown).Select
Else
ActiveCell.Offset(1, 0).Select
End If
End Sub
The problem is your activecell is in the wrong column. You need to address that:
Private Sub CommandButton3_Click() 'Next step button - selects next step in A column
Dim n As Long, fixed_range As Range
Set fixed_range = ActiveSheet.Cells(ActiveCell.Row, 1)
n = Cells(Rows.Count, fixed_range.Column).End(xlUp).Row
If fixed_range.Row = n Then MsgBox "Last one, no more instructions.": Exit Sub
If fixed_range.Offset(1, 0) = "" Then
fixed_range.End(xlDown).Select
Else
fixed_range.Offset(1, 0).Select
End If
End Sub
This uses a "fixed_range" to make sure we're working on column 1.

How to apply a condition to "used range" in whole column as a loop in excel using VBA?

I am beginner at VBA, I am stuck plz help. In this image(linked at the end of paragraph), I am trying to insert line above the cells which contains different name than the name of upper cell. Plz tell me if there is an easier way to do this or how to apply the given if else condition to whole "G" Column...
Still I am adding my code below if you don't need the image...
Sub ScanColumn()
'Application.ScreenUpdating = False
Dim varRange As Range
Dim currentCell As String
Dim upperCell As String
Dim emptyCell As String
currentCell = ActiveCell.Value
bottomCell = ActiveCell.Offset(1, 0).Value
emptyCell = ""
Dim intResult As Integer
intResult = StrComp(bottomCell, currentCell)
Dim emptyResult As Integer
emptyResult = StrComp(currentCell, emptyCell)
'I want to apply below condition to whole G column in used range
If emptyResult = 0 Then
ActiveCell.Select
ElseIf intResult = 0 Then
ActiveCell.Offset(1, 0).Select
Else
ActiveCell.Offset(1).EntireRow.Insert
ActiveCell.Offset(2, 0).Select
End If
End Sub
Here you have, just call the function "evaluateColumn" and pass the parameters, as example the "trial" sub.
Function evaluateColumn(column As String, startRow As Long, wsh As Worksheet)
Dim lastRow As Long
lastRow = wsh.Range(column & wsh.Rows.Count).End(xlUp).Row
Dim i As Long: i = startRow
Do While i < lastRow
If wsh.Cells(i, column).Value <> wsh.Cells(i + 1, column).Value And wsh.Cells(i, column).Value <> "" And wsh.Cells(i + 1, column).Value <> "" Then
wsh.Range(column & i + 1).EntireRow.Insert shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
i = i + 1
lastRow = lastRow + 1
End If
i = i + 1
Loop
End Function
Sub trial()
evaluateColumn "G", 2, ThisWorkbook.Worksheets("Sheet2")
End Sub
As you can see from the difference between my answer and the one below, your question isn't entirely clear. My code is an event procedure. It will run automatically, as you select a cell within the used range of column G.
If the value of the selected cell is the same as the cell below it the next row's cell will be selected.
If there is a value in either of the two cells, a blank row will be inserted and that row's cell selected. (If you want another row enable the row below the insertion.)
If either of the above conditions are true, do nothing and proceed with the selection the user made.
In order to let this code work it must be installed in the code sheet of the worksheet on which you want the action. It will not work if you install it in a standard code module, like Module1.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim TriggerRange As Range
Dim Off As Long ' offset from Target for selection
' if more than one cell is selected choose the first cell
If Target.Cells.CountLarge > 1 Then Set Target = ActiveCell
Set TriggerRange = Range(Cells(2, "G"), Cells(Rows.Count, "G").End(xlUp))
' this code will run only if a cell in this range is selected
' Debug.Print TriggerRange.Address(0, 0)
If Not Application.Intersect(Target, TriggerRange) Is Nothing Then
Application.EnableEvents = False
With Target
If .Value = .Offset(1).Value Then
Off = 1
ElseIf WorksheetFunction.CountA(.Resize(2, 1)) Then
Rows(.Row).Insert
' Off = 1 ' or -1 to change the selection
End If
.Offset(Off).Select
End With
Application.EnableEvents = True
End If
End Sub

How to continue the sequence of the unique numbers in the excel sheet after closing the userform?

I am facing a problem in getting the sequence of the unique numbers(Serial number) when the userform is closed and opened later on. Firstly, when I fill the data in the userform everything is captured in the excel sheet perfectly with correct sequence; if I close the userform and run the code by filling the userform with new data the unique ID's are again starting from "1" but not according to the excel sheet row number which was previously saved.
Below is the code I tried:
Private Sub cmdSubmit_Click()
Dim WB As Workbook
Dim lr As Long
Set WB = Workbooks.Open("C:\Users\Desktop\Book2.xlsx")
Dim Database As Worksheet
Set Database = WB.Worksheets("Sheet1")
eRow = Database.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
lr = Database.Range("a65536").End(xlUp).Row
With Sheets("Sheet1")
If IsEmpty(.Range("A1")) Then
.Range("A1").Value = 0
Else
Database.Cells(lr + 1, 1) = Val(Database.Cells(lr, 1)) + 1
End If
End With
Database.Cells(eRow, 4).Value = cmbls.Text
Database.Cells(eRow, 2).Value = txtProject.Text
Database.Cells(eRow, 3).Value = txtEovia.Text
Database.Cells(eRow, 1).Value = txtUid.Text
Call UserForm_Initialize
WB.SaveAs ("C:\Users\Desktop\Book2.xlsx")
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim maxNumber
If Not Intersect(Target, Range("B:B")) Is Nothing Then
' don't run when more than one row is changed
If Target.Rows.Count > 1 Then Exit Sub
' if column A in the current row has a value, don't run
If Cells(Target.Row, 1) > 0 Then Exit Sub
' get the highest number in column A, then add 1 and write to the
' current row, column A
maxNumber = Application.WorksheetFunction.Max(Range("A:A"))
Target.Offset(0, -1) = maxNumber + 1
End If
End Sub
Private Sub UserForm_Initialize()
With txtUid
.Value = Format(Val(Cells(Rows.Count, 1).End(xlUp)) + 1, "0000")
.Enabled = False
End With
With txtProject
.Value = ""
.SetFocus
End With
End Sub
In this image if you see unique id's are repeating 1 and 2, but I need as 1,2,3,4....
I think this is where the issue is coming from. You need to re-calculate the last row every time the user form is Initialized.
Private Sub UserForm_Initialize()
Dim ws as Worksheet: Set ws = Thisworkbook.Sheets("Database")
With txtUid
.Value = Format(ws.Range("A" & ws.Rows.Count).End(xlUp) + 1, "0000")
.Enabled = False
End With
With txtProject
.Value = ""
.SetFocus
End With
End Sub
It's always risky to use row numbers or [max range value +1] as a sequence number.
Safer to use something like a name scoped to the worksheet, which has a value you can increment. Then the sequence is independent of your data.
E.g.
Function GetNextSequence(sht As Worksheet) As Long
Const SEQ_NAME As String = "SEQ"
Dim nm As Name, rv As Long
On Error Resume Next
Set nm = sht.Names(SEQ_NAME)
On Error GoTo 0
'add the name if it doesn't exist
If nm Is Nothing Then
Set nm = sht.Names.Add(Name:=SEQ_NAME, RefersToR1C1:="=0")
End If
rv = Evaluate(nm.Value) + 1
nm.Value = rv
GetNextSequence = rv
End Function

How to add Selected Value (one at a time) from Listbox to specific excel column

I am using a Listbox which contains the name of folders. I need to select the names from listbox (one at a time, to maintain the order of selection) and add it to the excel column A1, such that each time adding to the next empty cell of column A. I am very new to vb and need help. Below are the approaches i tried.
Approach 1)
Sub AddRecord_Click()
With Sheet1.ListBox1
For intIndex = 0 To .ListCount - 1
With ActiveSheet
LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
End With
If .Selected(intIndex) Then
Sheet1.Cells(LastRow, "A") = Sheet1.ListBox1.Value
NextRow = LastRow + 1
End If
Next
End With
End Sub
Approach 2)
Sub AddRecord_Click()
intRecord = (CInt(Range("A1").End(xlDown).Row) + 1)
Sheet1.Cells(intRecord, "A") = Sheet1.ListBox1.Value
intRecord = intRecord + 1
End Sub
Try this may be helpful to u
Sub ListBox7_Change()
Dim i As Long
With ActiveSheet.ListBoxes("List Box 7")
For i = 1 To .ListCount
If .Selected(i) Then
Range("A" & Rows.count).End(xlUp).offset(1).Value = .List(i)
End If
Next i
End With
End Sub
First you get last used row from the excel sheet and finally increment that last row and insert next column value to the excel.
Dim last as Excel.Range = xlWorkSheet.Cells.SpecialCells
(Excel.XlCellType.xlcellTypeLastCell,Type.Missing)
dim lastUsedRow As Integer = last.Row
lastUsedRow += 1
xlWorksheet.RangeA("A"+ lastUserRow).value = ListBox1.Value

Return on Textbox1 value based upon two criterias in combobox and label

hope u're well. Need an expert help after trying a lot without sucess, please.
I have a price list in Sheet1 with 3 columns:
Medical Procedure
Type
Value of Procedure
In a userform, I need to return in Textbox1 the value of the procedure based on the criteria selected in combobox1 (with values that can be found in Medical Procedure column in Sheet1) and the caption in label1 (wich alrealdy is populated with a value that can be encounter in the Type column in Sheet1).
I tried this found here in stackoverflow from the user B Hart (thanks, B Hart!), but I wasn't able to change it to return in a textbox as a numerical value (this vba insert the found value in a listbox instead). Another issue is that the criteria below is in two combobox. I need the two criterias to be in a combobox and another in a label.
Private Sub GetCondStrandValue()
Dim iRow As Long
Dim strValue As String
strValue = vbNullString
If Me.ComboBox1.Value = vbNullString Or Me.ComboBox2.Value = vbNullString Then Exit Sub
With Planilha1
For iRow = 2 To .Range("A65536").End(xlUp).Row
If StrComp(.Cells(iRow, 1).Value, Me.ComboBox1.Value, 1) = 0 And _
StrComp(.Cells(iRow, 2).Value, Me.ComboBox2.Value, 1) = 0 Then
strValue = .Cells(iRow, 3).Value
Exit For
End If
Next
End With
If strValue = vbNullString Then Exit Sub
With Me.ListBox1
'If you only want a single value in the listbox un-comment the .clear line
'Otherwise, values will continue to be added
'.Clear
.AddItem strValue
.Value = strValue
.SetFocus
End With
End Sub
Maybe something like this:
Private Sub combobox1_Change()
Dim lastRow As Integer
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
With Me
For r = 2 To lastRow
If Sheets("Sheet1").Cells(r, 1) = .ComboBox1.Value And Sheets("Sheet1").Cells(r, 2) = .Label1.Caption Then
.TextBox1.Text = Sheets("Sheet1").Cells(r, 3)
Exit For
End If
Next
End With
End Sub

Resources