Find value in column and change cell to left with an if statment - vba

This VBA script should take the value in the cell A37 and check if its in the C column of another worksheet. When the number is found the column to the left should be changed to 0. If it is already 0 then a message box will inform the user and if the number does not exist another message box will inform them of this.
This is the VBA I am using to accomplish this. However, every time I try to run it there is a "compile error: Next without For"
Update This issue now is that I need to activate the cell that the fcell is in before doing an Active.cell offset
Sub Cancelled()
Dim x As Long
Dim regRange As Range
Dim fcell As Range
x = ThisWorkbook.Sheets("Welcome").Range("A37").Value
Set regRange = ThisWorkbook.Sheets("Registration").Range("C:C")
For Each fcell In regRange.Cells
If fcell.Value = x Then
ActiveCell.Offset(0, -1).Select
If ActiveCell.Value = 1 Then
ActiveCell.Value = 0
MsgBox "Changed to zero"
Exit Sub
Else
MsgBox "That registration number is already cancelled"
Exit Sub
End If
End If
Next fcell
MsgBox "That number does not exist"
End Sub

Edit for new question: No need to use Select and ActiveCell
If fcell.Value = x Then
If fcell.Offset(0,-1).Value = 1 Then
fcell.Offset(0,-1).Value = 0
...
Edit 2: A further suggestion: You could also use the Range.Find method. This will throw an error if nothing is found so you have to catch that:
On Error Resume Next 'If an error occurs, continue with the next line
Set fcell = regRange.Find(x)
On Error GoTo 0 'disable the error handler
If fcell Is Nothing Then 'If Find failed
MsgBox "That number does not exist"
Else
'do your stuff with fcell here
End If

Hope this is not too late to answer your question:
Sub Cancelled()
Dim x As Long
Dim regRange As Range
Dim fcell As Range
x = ThisWorkbook.Sheets("Welcome").Range("A7").Value
Set regRange = ThisWorkbook.Sheets("Registration").Range("C:C")
For Each fcell In regRange.Cells
If fcell.Value = x Then
If fcell.Offset(0, -1).Value = 1 Then
fcell.Offset(0, -1).Value = 0
MsgBox "Changed to zero"
Else
MsgBox "That registration number is already cancelled"
End If
Exit Sub
End If
Next fcell
MsgBox "That number does not exist"
End Sub
Instead of
Set regRange = ThisWorkbook.Sheets("Registration").Range("C:C")
its better to get the last row in Column C and then set your range as:
Dim lastRow As Long
lastRow = ThisWorkbook.Sheets("Registration").Cells(Rows.Count, "C").End(xlUp).Row
Set regRange = ThisWorkbook.Sheets("Registration").Range("C1:C" & lastRow)

Related

Check if a value is present in a range or not with VBA

I'm looking to check if a value is present in a range or not. If it's not there then I want it to jump to WriteProcess else I want it to give a message box saying it's present and exit the sub.
This is code,
'Write the Selected Value in the Range - Next Available row in the Column of Source
For i = TableStartingRow + 1 To AddNewEntrow
If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then
MsgBox "The data exists in the Table"
GoTo StopSub
Else
GoTo WriteProcess
End If
Next
WriteProcess:
wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value
StopSub:
'Turn on the ScreenUpdate
Application.ScreenUpdating = True
Please share your thoughts. Thanks.
Your problem is that if the loop expires (exhausts all of the iterations) there is no control to prevent it from entering the WriteProcess.
This is one problem with using GoTo statements. Preferably keep these to a minimum. For example, although this doesn't check every row, just an example of how you might avoid the extra GoTo.
'Write the Selected Value in the Range - Next Available row in the Column of Source
For i = TableStartingRow + 1 To AddNewEntrow
If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then
MsgBox "The data exists in the Table"
GoTo StopSub
Else
wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value
End If
Next
StopSub:
'Turn on the ScreenUpdate
Application.ScreenUpdating = True
However, a brute-force iteration over the table data seems unnecessary and if you need to check all rows int he table it's probably better to just use the Find method.
Assuming EntryColLet is a string representing the column letter:
Dim tblRange as Range
Dim foundRow as Range
Set tblRange = Range(EntryColLet & (TableStartingRow+1) & ":" & EntryColLet & AddNewEntRow)
Set foundRow = tblRange.Find(wb21Tool.Sheets("Home").ComboBox1.Value)
If foundRow Is Nothing Then
'The value doesn't exist in the table, so do something
'
Else
'The value exists already
MsgBox "The data exists in the Table"
GoTo StopSub
End If
'More code, if you have any...
StopSub:
Application.ScreenUpdating = True
And regarding the remaining GoTo -- if there's no more code that executes after the condition If foundRow Is Nothing then you can remove the entire Else clause and the GoTo label:
Dim tblRange as Range
Dim foundRow as Range
Set tblRange = Range(EntryColLet & (TableStartingRow+1) & ":" & EntryColLet & AddNewEntRow)
Set foundRow = tblRange.Find(wb21Tool.Sheets("Home").ComboBox1.Value)
If foundRow Is Nothing Then
'The value doesn't exist in the table, so do something
End If
Application.ScreenUpdating = True
End Sub
Alternate solution if you need to check every row before performing the "WriteProcess":
Dim bExists As Boolean
bExists = False
'Write the Selected Value in the Range - Next Available row in the Column of Source
For i = TableStartingRow + 1 To AddNewEntrow
If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then
bExists = True
MsgBox "The data exists in the Table"
Exit For
End If
Next
If Not bExists Then wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value
'Turn on the ScreenUpdate
Application.ScreenUpdating = True

Run-Time Error 91: Can't run through the second line

Here is part of the code I am working on which is a part of a macro.
This is also the same on another file which is basically the same also.
The macro works on the other file while on the other, it doesn't and comes with the Run-time error '91'.
Attached is the code:
shtData.Activate
Dim r As Integer
Dim strassured As String
r = 1
While ActiveSheet.Cells(r, 1) <> ""
ActiveSheet.Cells(r, 1).Select
strassured = ActiveCell.Value
If shtWorkSpace.Range("B3").Value = strassured Then
If shtWorkSpace.Range("A60").Value = "Pending" Then
DataHandling.OverwriteDataTab (strassured)
Exit Sub
Else
MsgBox "This assured name is already in the database. Assured Names must be unique!", vbCritical
shtWorkSpace.Activate
ActiveSheet.Range("A1").Select
Exit Sub
End If
Else
r = r + 1
End If
Wend
I've added an answer, not to provide how to define and Set both worksheets (shtData and shtWorkSpace).
But also to provide a better coding practice, there is no need to Activate worksheets, or use Select and ActiveCell. Instead use fully qualified Ranges and Worksheets.
Code
Sub Test()
Dim shtData As Worksheet
Dim shtWorkSpace As Worksheet
Dim r As Integer
Dim strassured As String
Set shtData = Worksheets("Data") '<-- modify "Data" to your sheet name
Set shtWorkSpace = Worksheets("Workspace") '<-- modify "Workspace" to your sheet name
r = 1
While shtData.Cells(r, 1) <> ""
strassured = shtData.Cells(r, 1).Value
If shtWorkSpace.Range("B3").Value = strassured Then
If shtWorkSpace.Range("A60").Value = "Pending" Then
DataHandling.OverwriteDataTab (strassured)
Exit Sub
Else
MsgBox "This assured name is already in the database. Assured Names must be unique!", vbCritical
shtWorkSpace.Activate
ActiveSheet.Range("A1").Select '<-- not sure why you need to select the sheet and Range("A1")
Exit Sub
End If
Else
r = r + 1
End If
Wend
End Sub

Unable to update the value in combobox to sheet

I am new to VBA Coding.I have an userform which retrieves the value from excel sheet.There is a combobox which retrieves the value.But i want to change the combobox value & save it in excel.....
Image for Data in Excel
Dim temp As String
Dim findid As String
Dim lkrange As Range
Set lkrange = Sheet6.Range("A:D")
findid = TextBox1.Value
On Error Resume Next
temp = Application.WorksheetFunction.Vlookup(findid, lkrange, 1, 0)
If Err.Number <> 0 Then
MsgBox "ID not found"
Else
MsgBox "ID found"
Label5.Caption = Application.WorksheetFunction.Vlookup(findid, lkrange, 2, 0)
Label6.Caption = Application.WorksheetFunction.Vlookup(findid, lkrange, 3, 0)
ComboBox1.Value = Application.WorksheetFunction.Vlookup(findid, lkrange, 4, 0)
End If
End Sub
Private Sub CommandButton2_Click()
Dim fid As String
Dim rowc As Integer
Dim rowv As Integer
fid = TextBox1.Value
rowc = Application.WorksheetFunction.Match(fid, Range("A:A"), 0)
rowv = rowc - 1
Cells(rowv, 4).Values = marktable.ComboBox1.Value
End Sub
you could try the following
Option Explicit
Private Sub CommandButton1_Click()
Dim lkrange As Range
Dim rng As Range
Set lkrange = ThisWorkbook.Sheets("Sheet6").Range("A:A")
With Me
Set rng = MyMatch(.TextBox1.Value, lkrange)
If rng Is Nothing Then
MsgBox "ID not found"
Else
MsgBox "ID found"
.Label5.Caption = rng.Offset(0, 1)
.Label6.Caption = rng.Offset(0, 2)
.ComboBox1.Text = rng.Offset(0, 3)
End If
End With
End Sub
Private Sub CommandButton2_Click()
Dim lkrange As Range
Dim rng As Range
Set lkrange = ThisWorkbook.Sheets("Sheet6").Range("A:A")
With Me
Set rng = MyMatch(.TextBox1.Value, lkrange)
If Not rng Is Nothing Then rng.Offset(0, 3).Value = .ComboBox1.Text
End With
End Sub
Private Function MyMatch(val As Variant, rng As Range, Optional matchType As Variant) As Range
Dim row As Long
If IsMissing(matchType) Then matchType = 0
On Error Resume Next
row = Application.WorksheetFunction.Match(val, rng, matchType)
If Err = 0 Then Set MyMatch = rng.Parent.Cells(rng.Rows(row).row, rng.Column)
End Function
there were some errors:
Sheet6.Range("A:D") is not vaild
if you want to point to a sheet named "Sheet6" belonging to the Workbook where the macro resides, then you have to use ThisWorkbook.Sheets("Sheet6").Range("A:A")
Cells(...,...).Values =... is not valid
you must use Cells(...,...).Value =
but I think the following suggestions are more important:
Always use Option Explicit statement at the very beginning of every module
this will force you to explicitly declare each and every variable, but then it'll save you lots of time in debugging process
avoid/limit the use of On Error Resume Next statement
and, when used, make sure to have it followed as soon as possible by the "On Error GoTo 0" one. that way you have constant control on whether an error occurs and where
I confined it in a "wrapper" function (MyMatch()) only.
Always specify "full" references when pointing to a range
I mean, Cells(..,..) implictly points to the active sheet cells, which may not always be the one you'd want to point to.

VBA Record date of row change in specific column

I'm trying to automatically update the "Updated" column of an excel spreadsheet when any cell of that specific row changes to today's date. I was able to do this by hard-coding where the "Updated" column header would be, however, it is now necessary to search for that column header as it may move.
The code I am trying to implement works but immediately gives me the error Automation error - The object invoked has disconnected from it's clients.
Any help would be appreciated. Here is the code I have currently:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:DX")) Is Nothing Then
Dim f As Range
Set f = ActiveSheet.Range("A1:DD1").Find("Updated", lookat:=xlWhole)
' f.Row = Range(Target).Row
If Not f Is Nothing Then
Range(Split(f.Address, "$")(1) & Target.Row).Value = Now
Else
MsgBox "'Updated' header not found!"
End If
End If
End Sub
You got into an endless loop.
Try this:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:DX")) Is Nothing Then
Dim f As Range
Set f = ActiveSheet.Range("A1:DD1").Find("Updated", lookat:=xlWhole)
' f.Row = Range(Target).Row
If f Is Nothing Then
MsgBox "'Updated' header not found!"
ElseIf Intersect(Target, f.EntireColumn) Is Nothing Then
Intersect(Target.EntireRow, f.EntireColumn).Value = Now
' Else
' MsgBox "We entered this function again because the row above updated the Updated column", vbInformation, "False alarm"
End If
End If
End Sub
To understand what happens,
Uncomment the else and MsgBox
Put a breakpoint on the MsgBox
When you hit it, press [ctrl]-L
In a case such as this, I run into far fewer problems when I simply loop through the available cells to find the column header. Using the .Find method also works, but is less "tunable" to my needs in a custom application.
Public Function FindColumn(header As String) As Long
Dim lastCol As Long
Dim headerCol As Long
Dim i As Long
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("VTO2 Labor")
lastCol = sh.Cells(1, sh.Columns.Count).End(xlToLeft).Column
headerCol = 0
For i = 1 To lastCol
If sh.Cells(1, i).Value = header Then
headerCol = i
End If
Next i
FindColumn = headerCol
End Function
It isn't clear on whether the Updated column header could be in row 1 or if it will always be in row 1, just not in the same location.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:DX")) Is Nothing Then
On Error GoTo bm_SafeExit
'TURN OFF EVENTS IF YOU ARE GOING TO WRITE A VALUE INTO THE WORKSHEET!
Application.EnableEvents = False
Dim uCol As Long, f As Range
If Application.CountIf(Rows(1), "updated") Then
uCol = Application.Match("updated", Rows(1), 0)
For Each f In Intersect(Target, Range("A:DX"))
If f.Row > 1 Then _
Cells(f.Row, uCol) = Now
Next f
Else
MsgBox "'Updated' header not found!"
End If
End If
bm_SafeExit:
Application.EnableEvents = True
End Sub
That should survive multiple updates (e.g. when pasting values). The problem I see is that is the Updated column is being shifted around, presumably through inserting columns or the like, then the change routine is going to run.

How to loop through an excel sheet from word

I am struggling to find out how i can loop through all rows in excel from word. What I want to achieve is that if there is something in the WP column in excel then save the active worddocument with that filename. However i cant figure out something simple as getting the last row(might be empty rows in between), i just get error code 424, which according to MSDN does not give me any real hint whats wrong. Any ideas whats wrong?
Public Sub test()
Dim xlapp As Object
Set xlapp = CreateObject("Excel.Application")
myFileName = "Z:\Dokumentstyring\UnderArbeid\PARTSLIST.xlsm"
xlapp.Workbooks.Open myFileName
xlapp.Application.ScreenUpdating = False
xlapp.Visible = False
a = xlapp.sheets("List").Range("A1").Value
b = firstBlankRow(xlapp)
c = getColumn("WP", xlapp)
xlapp.Application.ScreenUpdating = True
xlapp.ActiveWorkbook.Close (True)
xlapp.Quit
Set xlapp = Nothing
End Sub
My function to receive the last row:
Function firstBlankRow(ByRef xlapp) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
With xlapp.sheets("List")
'~~> Check if there is any data in the sheet
'If xlapp.WorksheetFunction.CountA(.Cells) <> 0 Then
firstBlankRow = .Range("A" & .Rows.Count).End(Excel.XlDirection.xlUp).Row
'Else
firstBlankRow = 1
'End If
End With
End Function
Here is my function for getting the column number
Public Function getColumn(header As String, ByRef xlapp) As Integer
Dim rng1 As Range
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, Columns.Count)).Find(header, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
getColumn = rng1.Column
Else
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End If
End With
End Function
As per our conversation in the comments, change Dim Rng1 As Range to
Dim Rng1 As Object.
You can find the actual values of XlDirection, Xlvalues, xlwhole enums.
Preferably, it's better to do it like this:
Private Const xlUp as long = -4162
'and so on
Edit1:
Here's an adjusted function that solves your problem (I've tested it on my machine)
Public Function getColumn(header As String, ByRef xlapp) As Long
Dim rng1 As Object
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, .Columns.Count))
If rng1 Is Nothing Then
MsgBox ("ERROR: Range object is empty.")
getColumn = -1
Exit Function
End If
For Each m In rng1
If m = "WP" Then
getColumn = m.Column
Exit Function
End If
Next m
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End With
End Function