Loop stops after one condition is met even if there are multiple - vba

The code below will "exit for" after it meets its condition once even if there are more in the range that meet the condition. How do I correct this?
Private Sub cmdAdd_Click()
On Error GoTo Whoa
Dim LastRow As Long, i As Long
LastRow = ActiveSheet.Range(Me.txtTaskCol.Value & Rows.Count).End(xlUp).Row
'Copy input values to sheet
For i = 1 To LastRow
If UCase(CStr(ActiveSheet.Range(Me.txtTaskCol.Value & i).Value)) = UCase(CStr(Me.txtTask.Value)) Then
ActiveSheet.Range(Me.txtUnitCol.Value & i).Value = Me.txtQuantity.Value
Exit For
Else
If i = LastRow Then MsgBox "Task Not Found!"
End If
Next i
'Clear input controls
Me.txtTask.Value = ""
Me.txtQuantity.Value = ""
Exit Sub
Whoa:
Select Case Err.Number
Case 1004
MsgBox "Check for Valid Column Letters!"
End Select
End Sub

Echoing K.Davis comment, not sure why you would want to exit?
I made some edits to your code. Error handling is not included, but the code should complete the loop and tell you if nothing is found.
Private Sub cmdAdd_Click()
On Error GoTo Whoa
Dim LastRow As Long, i As Long
LastRow = ActiveSheet.Range(Me.txtTaskCol.Value & Rows.Count).End(xlUp).Row
'Set a counter so you can message Task Not Found
Dim matchCounter as Integer
matchCounter = 0
'Copy input values to sheet
For i = 1 To LastRow
If UCase(CStr(ActiveSheet.Range(Me.txtTaskCol.Value & i).Value)) = _
UCase(CStr(Me.txtTask.Value)) Then
ActiveSheet.Range(Me.txtUnitCol.Value & i).Value = Me.txtQuantity.Value
matchCounter = matchCounter + 1
End If
Next i
If matchCounter = 0 then MsgBox "Nothing Found"
'Clear input controls
Me.txtTask.Value = ""
Me.txtQuantity.Value = ""
Exit Sub
End Sub
Hope it's helpful.

Just use a boolean flag that will set the flag to True if your If...Then statement is true one time:
If you are wanting to continue your For...Next statement after you meet the criteria, then you don't want to exit for.
Private Sub cmdAdd_Click()
On Error GoTo Whoa
Dim LastRow As Long, i As Long, tskFlg As Boolean
LastRow = ActiveSheet.Range(Me.txtTaskCol.Value & Rows.Count).End(xlUp).Row
'Copy input values to sheet
For i = 1 To LastRow
If UCase(CStr(ActiveSheet.Range(Me.txtTaskCol.Value & i).Value)) = UCase(CStr(Me.txtTask.Value)) Then
ActiveSheet.Range(Me.txtUnitCol.Value & i).Value = Me.txtQuantity.Value
tskFlg = True
End If
Next i
If tskFlg = False Then MsgBox "Task Not Found!"
'Clear input controls
Me.txtTask.Value = ""
Me.txtQuantity.Value = ""
Exit Sub
Whoa:
Select Case Err.Number
Case 1004
MsgBox "Check for Valid Column Letters!"
End Select
End Sub

Related

Check if mandatory fields are not empty before each Save in Macro

I have a scenario in which I have to check if Column A is not empty, corresponding row values in other columns should not be empty. If they are, I want an error message to be thrown.
So I came up with this.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long, lngTCols As Long
Dim lngRowCheck(1 To 5) As String
For Each rngCell In Range("A1:A" & lngLstRow)
If Not IsEmpty(rngCell.Value) Then
lngRowCheck(1) = "C"
lngRowCheck(2) = "F"
lngRowCheck(3) = "G"
lngRowCheck(4) = "J"
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To UBound(lngRowCheck)
For Each rngCell In Range(lngRowCheck(i) & "2:" & lngRowCheck(i) & lngLstRow)
If rngCell.Value = 0 Then
MsgBox ("Please enter a name in cell " & rngCell.Address)
rngCell.Select
End If
Next
Next i
Next
End Sub
However, this doesn't work and the validation doesn't happen before each save and I'm not able to debug this as well. Any help? Am I doing something wrong?
Try something like this...
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Dim rngCell As Range, cell As Range
Dim lngLstRow As Long, lngTCols As Long
Dim lngRowCheck(1 To 5) As String
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For Each rngCell In Range("A1:A" & lngLstRow)
If Not IsEmpty(rngCell.Value) Then
lngRowCheck(1) = "C"
lngRowCheck(2) = "F"
lngRowCheck(3) = "G"
lngRowCheck(4) = "J"
For i = 1 To UBound(lngRowCheck)
For Each cell In Range(lngRowCheck(i) & "2:" & lngRowCheck(i) & lngLstRow)
If cell.Value = 0 Then
MsgBox "Please enter a name in cell " & cell.Address(0, 0)
cell.Select
Cancel = True
Exit Sub
End If
Next cell
Next i
End If
Next rngCell
End Sub

Run-time error 1004 in Excel macro: Application-defined or object-defined error

I'm trying to use this code to search for something in one sheet and move it to another. Below is my code. I keep getting this error:
Run-time error '1004':
Application-defined or object-defined error
Code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet, myCounter
Dim erow, myValue As Long
For Each ws In Sheets
If ws.Range("C3").Value > 6 Then
myCounter = 1
ws.Select
ws.Range("C3").Select
myValue = ws.Range("C3").Value
Worksheets("Report").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(x1Up).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1) = myValue
nextValue = MsgBox("Value found in " & ws.Name & Chr(10) & "Continue?", vbInformation + vbYesvbNo, ws.Name & " C3 = " & ws.Range("C3").Value)
Select Case nextValue
Case Is = vbYes
Case Is = vbNo
Exit Sub
End Select
End If
Next ws
If myCounter = 0 Then
MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found"
End If
End Sub
Why am I getting this error?
**Run-time error '1004':
Application-defined or object-defined error**
You have x1Up where you should have xlUp; note the 1 instead of the lower case L. Also the MsgBox option is vbYesNo, not vbYesvbNo.
Option Explicit
Private Sub CommandButton1_Click()
Dim w As Long, bFound As Boolean, nextValue As Variant
Dim erow, myValue As Long
For w = 1 To Worksheets.Count
With Worksheets(w)
'don't look on the Report worksheet
If .Name <> Worksheets("Report").Name Then
'use isnumeric to avoid confusing text and numbers
If IsNumeric(.Range("C3").Value2) Then
If .Range("C3").Value2 > 6 Then
Worksheets("Report").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = .Range("C3").Value
nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value)
bFound = True
Select Case nextValue
Case vbYes
'do nothing; continue
Case vbNo
'just exit the worksheet loop
Exit For
End Select
End If
End If
End If
End With
Next w
If Not bFound Then
MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found"
End If
End Sub
The above is my version of your code. Get used to using Option Explicit to avoid typos.

Excel macros programming search

Can you help me with edit macro? I would like to search on another sheet but I don't known what I do wrong. Sheet where I would like to search is "Díly".
Sub díly()
Dim rngVis As Range
Dim VisCell As Range
Dim sFind As String
sFind = InputBox("Naskenujte zákaznické císlo.")
If Len(Trim(sFind)) = 0 Then Exit Sub 'Pressed cancel
Application.ScreenUpdating = False
With Intersect(Sheets("Díly").UsedRange, Sheets("Díly").Columns("A"))
.AutoFilter 1, sFind
On Error Resume Next
Set rngVis = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
.AutoFilter
End With
Application.ScreenUpdating = True
If rngVis Is Nothing Then
MsgBox sFind & " Nenalezeno."
Else
For Each VisCell In rngVis.Cells
MsgBox "Naskenované císlo: " & VisCell.Sheets("Díly").Cells(VisCell.Row, "A").Text & vbNewLine & _
"Vyhledáno: " & VisCell.Sheets("Díly").Cells(VisCell.Row, "B").Text
Next VisCell
End If
End Sub
try this
Option Explicit
Sub díly()
Dim rngVis As Range
Dim VisCell As Range
Dim sFind As String
sFind = InputBox("Naskenujte zákaznické císlo.")
If Len(Trim(sFind)) = 0 Then Exit Sub 'Pressed cancel
Application.ScreenUpdating = False
With Intersect(Sheets("Díly").UsedRange, Sheets("Díly").Columns("A"))
.AutoFilter 1, sFind
On Error Resume Next
Set rngVis = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
.AutoFilter
End With
Application.ScreenUpdating = True
If rngVis Is Nothing Then
MsgBox sFind & " Nenalezeno."
Else
For Each VisCell In rngVis.Cells
MsgBox "Naskenované císlo: " & VisCell.Text & vbNewLine & _
"Vyhledáno: " & VisCell.Offset(, 1).Text
Next VisCell
End If
End Sub

VBA Excel "Object Required" error

My codes gives me a Object Required 424 error on this line:
lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row
My full code:
Private Sub Worksheet_Change(ByVal Target As Range)
' If Target.Count > 1 Then Exit Sub
' If Target.Column > 2 Then Exit Sub
Application.EnableEvents = False
If Target.Column = 6 Then
If Target.Offset(0, 1).Value <> "" Then
MsgBox "You must only fill in one of the two columns"
Target.ClearContents
GoTo ExitSub
End If
End If
If Target.Column = 7 Then
If Target.Offset(0, -1).Value <> "" Then
MsgBox "You must only fill in one of the two columns"
Target.ClearContents
GoTo ExitSub
End If
End If
Dim arrData() As Variant
Dim i As Long
Dim lngRow As Long
Dim myNum As Variant
Dim ws As Worksheet
myNum = Target.Value
If Target.Column = 6 Then
With BogieInspectionPoints 'this is a sheet name
lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row
arrData = .Range("a1:b" & lngRow)
End With
End If
If Target.Column = 7 Then
With WagonInspectionPoints 'this is a sheet name
lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row
arrData = .Range("a1:b" & lngRow)
End With
End If
For i = 1 To lngRow
If myNum = arrData(i, 1) Then
Cells(Target.Row, 8).Value = arrData(i, 2)
Exit For
End If
Next
ExitSub:
Application.EnableEvents = True
End Sub
It looks like those sheet variables aren't set.
You will need to add this at the top.
Dim BogieInspectionPoints as Worksheet
Dim WagonInspectionPoints as Worksheet
Set BogieInspectionPoints = ActiveWorkbook.Sheets("BogieInspectionPoints")
Set WagonInspectionPoints = ActiveWorkbook.Sheets("WagonInspectionPoints")
I was assuming there was other code. When you add this line all the With statements should process correctly using the code you posted.
What you're doing with the With statements is shorthanding the object. Instead of writing
BogieInspectionPoints.Range("A1")
'More code
You can write
With BogieInspectionPoints
.Range("A1")
End With
It keeps you from having to write the full object name out.

Copy excel row in different worksheet when cell dropdown "Yes" and when "No" removes the row if "Yes" was selected previously

I am trying to copy excel row in different worksheet sheet 2 when cell dropdown "Yes" of Column F and when "No" removes the row if "Yes" was selected previously. I also wanted to check if duplicate exists in worksheet 2, then prompt user with "Yes", "No" button. If "Yes" then duplicate if "No" do nothing.
ColA:Customer Name ColB:Customer Address ColC:Customer City ColD:Cust zip ColE:Tel ColF:Yes/No
I have tried this.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lastrow As Long
If UCase(Range("F" & ActiveCell.Row).Value) <> "YES" Then Exit Sub
With ThisWorkbook.Worksheets("Sheet2")
lastrow = Application.Max(4, .Cells(.Rows.Count, "A").End(xlUp).Row + 1)
If WorksheetFunction.CountIf(.Range("A1:A" & lastrow), _
Range("A" & ActiveCell.Row).Value) > 0 Then Exit Sub
Response = MsgBox("Record already exists, add again?", vbQuestion + vbYesNo + 256)
If Response = vbNo Then Exit Sub
.Range("A" & lastrow).Resize(, 5).Value = _
Range("A" & ActiveCell.Row).Resize(, 5).Value
End With
Response = MsgBox("Record added")
End Sub
If I understand you correctly, you need something like this (code runs only if changed value in column F):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastrow As Long
Dim Response
Dim rng As Range, rngToDel As Range
Dim fAddr As String
If Intersect(Target, Range("F:F")) Is Nothing Then Exit Sub
Application.EnableEvents = False
On Error GoTo ErrHandler
With ThisWorkbook.Worksheets("Sheet2")
lastrow = Application.Max(4, .Cells(.Rows.Count, "A").End(xlUp).Row + 1)
If UCase(Target.Value) = "YES" Then
Response = vbYes
If WorksheetFunction.CountIf(.Range("A1:A" & lastrow), _
Range("A" & Target.Row).Value) > 0 Then
Response = MsgBox("Record already exists, add again?", vbQuestion + vbYesNo + 256)
End If
If Response = vbYes Then
.Range("A" & lastrow).Resize(, 5).Value = _
Range("A" & Target.Row).Resize(, 5).Value
MsgBox "Record added"
End If
ElseIf UCase(Target.Value) = "NO" Then
With .Range("A4:A" & lastrow)
Set rng = .Find(What:=Range("A" & Target.Row), _
LookIn:=xlValues, _
lookAt:=xlWhole, _
MatchCase:=False)
If Not rng Is Nothing Then
fAddr = rng.Address
Do
If rngToDel Is Nothing Then
Set rngToDel = rng.Resize(, 5)
Else
Set rngToDel = Union(rngToDel, rng.Resize(, 5))
End If
Set rng = .FindNext(rng)
If rng Is Nothing Then Exit Do
Loop While fAddr <> rng.Address
End If
If Not rngToDel Is Nothing Then
rngToDel.Delete Shift:=xlUp
MsgBox "Records from sheet2 removed"
End If
End With
End If
End With
ExitHere:
Application.EnableEvents = True
Exit Sub
ErrHandler:
Resume ExitHere
End Sub