VBA excel, if Cells(counter,1)="text" then - vba

I'm trying to execute an if statement that only activates if a certain cell contains a specific text. The cell in question needs to be dynamically altered based on a integer that will change, so far ive tried multiple methods but nothing seems to work.
If Cells(counter, 1).text = "text" then
If Cells(counter, 1).value = "text" then
If Range(Cells(counter, 1)).text = "text then
If Range(Cells(counter, 1)).value = "text then
This seems like a simple procedure, does someone have a solution?
Thanks, Sporre
Edit:
Private Sub CheckBox_Change()
If CheckBox.Value = True Then
'do stuff
End If
ElseIf CheckBox.Value = False Then
If Cells(1, counter).Value = "text1" Or Cells(1, counter).Value =
"text2" Or Cells(1, counter).Value = "text3" Then
'do stuff
End If
End If
End Sub
This is where i get the error message "Application-definded or Object-defined error".
Edit 2:
The problem was I tried to call for the counter in several different subs and it was not a public integer. Thanks for your help!

This one will work
if (Trim(ThisWorkbook.Worksheets("Sheet1").Cells(counter, 1).Value)="text") Then

You cannot use End If and then follow up with and ElseIf. The first one ends the If statement entirely, meaning that the you would have to begin a new one. Based on you edit, I think your code should look something like this:
Private Sub CheckBox_Change()
If CheckBox.Value = True Then
'do stuff
ElseIf CheckBox.Value = False Then
If (Counter < 1) Then
'Show an error if the counter is less than 1
MsgBox "Error: Counter less than 1", vbCritical
ElseIf Cells(1, counter).Value = "text1" Or Cells(1, counter).Value = "text2" Or Cells(1, counter).Value = "text3" Then
'do stuff
End If
End If
End Sub

This should work:
If Worksheets("Name of your worksheet").Cells(counter, 1).Value)="text" Then
'execute some code
End if

Related

VBA Replace() not working

The command Replace() does not work for me. I finally got it working but only by skipping over error messages. Why a command works with when there are errors, dont ask, here is my working code. Can anyone please explain where im going wrong?
If Target.Address(0, 0) = "E3" Then
Range("E3").Select
On Error Resume Next
Selection.NumberFormat = "#"
Selection.Replace What:="-", Replacement:=""
Selection.Replace What:=" ", Replacement:=""
Selection = UCase(Selection.Value)
End If
Also, why wouldn't something like this work?
selection.value = replace(selection.value," ", "")
A bit of context for those who want: I'm using this to remove " - " and spaces out of product style numbers automatically. eg 05402-pt072 004 needs to equal 05402pt072004.
Thanks to anyone who responds.
Given the existence of Target I assume the code is in a Worksheet_Change event.
That said, the following should work:
If Target.Address(0, 0) = "E3" Then
Application.EnableEvents = False 'stop change event from firing again
With Target
.NumberFormat = "#"
.Replace What:="-", Replacement:=""
.Replace What:=" ", Replacement:=""
.Value = UCase$(.Value)
End With
Application.EnableEvents = True
End If
I am assuming you are running into an infinite loop, as each time you update the targetcell, the worksheet_change event kicks in.
How about
Private Sub Worksheet_Change(ByVal Target As Range)
Dim s As String
If Target.Address = "$E$3" Then
Application.EnableEvents = False
s = Target
s = Replace(s, " ", "")
s = Replace(s, "-", "")
Target = Format(s, "#")
Application.EnableEvents = True
End If
End Sub
On a new Excel worksheet write this:
Sub TestMe()
Range("A1") = "05402-pt072 004"
Stop
Range("A1").Value = Replace(Range("A1").Value, " ", "")
Stop
Range("A1").Value = Replace(Range("A1").Value, "-", "")
End Sub
Then press F5. The 05402-pt072 004 appears on A1
Press F5. Now the text on A1 is 05402-pt072004.
Press F5. Now the text on A1 is 05402pt072004.
Enjoy!
As a next step, you may remove the .Value from the code. Then try to write With Range("A1") etc.
This will also work:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$E$3" Then
Target.NumberFormat = "#"
Value = Target.Value
Value = Replace(Value, "-", "")
Value = Replace(Value, " ", "")
Target.Value = UCase(Value)
End If
End Sub
Try replacing your code with the following
If Not Application.Intersect(Target, Me.Range("E3")) Is Nothing Then
With Target
.NumberFormat = "#"
Replace expression:=.Value2, Find:="-", Replace:=vbNullString
Replace expression:=.Value2, Find:=" ", Replace:=vbNullString
.Value2 = UCase(.Value2)
End With
End If

Delete Excel row if Listbox is selected

Hi I need help with my code it supposed to delete the rows in my
sheets once the item is selected in the listbox, it is kind of strange when I run it it didn't delete the item I selected but it deleted the one above it:
Private Sub clearselected()
Dim I As Long
On Error Resume Next
With ListBox1
For I = .ListCount - 1 To 0 Step -1
If .Selected(I) Then
.RemoveItem I
With Sheets("Expenses")
.Rows(I + 2).EntireRow.Delete
.Shape("Listbox1").ControlFormat.ListFillRange = _
.Range("B:B").Address
End With
End If
todaysDate.Text = ""
TextBox11.Text = ""
TextBox13.Text = ""
TextBox12.Text = ""
TextBox4.Text = ""
Next I
End With
End Sub
As mentioned in the comments, you should change i+2 to i+3, because of the different starting index of the row and the ListBox.
However, whenever you have a problem like this, simply try some "advanced" debugging, telling you exactly what is happening:
With Sheets("Expenses")
MsgBox (i + 2 & " is going to be deleted!")
.Rows(i + 2).EntireRow.Delete 'or just .Rows(i + 2).Delete
.Shape("Listbox1").ControlFormat.ListFillRange = _
.Range("B:B").Address
End With
Thus, before deleting you will see the MsgBox, telling you what is going to happen. If you are not happy with it, it is easy to change i+2 to i+3 and etc.

Hiding Empty Cells

I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :
Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate
For i = 1 To po
s = i & ":" & i
If IsEmpty(Cells(i, 1).Value) Then
Rows(s).Select
Selection.EntireRow.Hidden = True
End If
Next
End Sub
The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.
You can even make your code shorter like this:
For i = 9 To 12
Cells(i, 1).EntireRow.Hidden = IsEmpty(Cells(i, 1).Value)
Next i
Thus, the result of the Hidden property would be dependent on whether the Cells(i,1) is empty. It is easier to understand and to maintain.
Check the solution below. In case you need to change your affected area, just change the value of targetRange.
Sub EmptyRow()
Dim targetRange as Range, po as Long, i as Long
Set targetRange = Range("A9:A12")
po = targetRange.Count
With targetRange
For i = 1 To po
If IsEmpty(.Cells(i, 1).Value) Then
.Rows(i).EntireRow.Hidden = True
End If
Next
End With
End Sub
Sheets("Sheet1").Range("A9:A12").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
SpecialCells results in run-time error if no cells are found, but that can be checked:
If [CountBlank(Sheet1!A9:A12)] Then _
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
or ignored:
On Error Resume Next
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
You can get rid of bits like select
Sub EmptyRow()
For i = 9 To 12
If IsEmpty(Cells(i, 1).Value) Then
Cells(i, 1).EntireRow.Hidden = True
End If
Next i
End Sub

How do I make VBA (excel) tell me the cell where my code stopped

I hope this is possible. I would like to know how to make excel tell me in what cell it encountered my predefined "error". For example part of the code is this:
Sub CheckErrors()
For Each Cel In Range("A3:A400")
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 6)) = True Then
Msgbox "Add a description (name) when creating"
End If
End If
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 7)) = True Then
Msgbox "Please choose type when creating"
Exit For
End If
End If
Next
I would like the message boxes to also include what specific cell excel found empty. So if in column A there is CR then column G has to have a description and I would like the message box to say "Add a description (name) when creating, revise cell G3" if G3 is empty while A3 has CR in it.
Any help is appreciated. Im very new to VBA and coding, so even the most basic might be helpful!
Regards
Jim
Well, you could add inside the MSGBOX the property .address... this way:
Sub CheckErrors()
For Each Cel In Range("A3:A400")
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 6)) = True Then
Msgbox "Add a description (name) when creating " & Cel.Offset(0, 6).address
End If
End If
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 7)) = True Then
Msgbox "Please choose type when creating " & Cel.Offset(0, 7).address
Exit For
End If
End If
Next
End Sub
Your question is vague and unclear, please provide more info about what you really want, what you did to achieve that, what errors you have, or any other results..
Edit
In the comment of Nick Dewitt you will see what you need to replace the $ in the address Replace(Cel.Offset(0, 6).address, "$", "")
Edit #2
Sub CheckErrors()
For Each Cel In Range("A3:A400")
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 6)) = True Then
Msgbox "Add a description (name) when creating " & Replace(Cel.Offset(0, 6).address, "$", "")
End If
End If
If Cel.Value = "CR" Then
If IsEmpty(Cel.Offset(0, 7)) = True Then
Msgbox "Please choose type when creating " & Replace(Cel.Offset(0, 6).address, "$", "")
Exit For
End If
End If
Next
End Sub

Screen out values which didn't fit two conditions

i wanna write a VBA programme that screen out values which didnt satisfy the specified values. However, I kinda stuck in the object-defined error of line 4 (If...Then). Would somebody pls help me out. Many thanks!!!!!!!!
Sub Macro1()
If Cells(A, 1) <> "none" Or Cells(A, 1) <> 0 Then
Cells(A, 2) = "checked"
Else
Cells(A, 2) = "Not checked"
End If
End Sub
You have your rows and columns reversed. Try:
Sub Macro1()
If Cells(1, "A") <> "none" Or Cells(1, "A") <> 0 Then
Cells(2, "A") = "checked"
Else
Cells(2, "A") = "Not checked"
End If
End Sub
A cell is referenced by a row and column or address. So use
Cells(1,1)
or
Cells("A1")
Use this:
Sub Macro1()
If Cells(1, 1) <> "none" Or Cells(1, 1) <> 0 Then
Cells(1, 2) = "checked"
Else
Cells(1, 2) = "Not checked"
End If
End Sub
Or you this:
Sub Macro2()
If Range("A1") <> "none" Or Range("A1") <> 0 Then
Range("B1") = "checked"
Else
Range("B1") = "Not checked"
End If
End Sub
You need to be careful to:
0) respect the language's syntax/semantics: is kind of obvious for a human, but what would mean A for VBA?
1) be sure what cell values are you accessing: i.e. which worksheet those cells belong to;
2) ynot compare apples with oranges: if something is a string, comparing it with an integer value gives you type mismatch errors. You need to be sure before comparing what type are you comparing.
3) follow the rules of Boolean logic, not the the ones common language logic: to say that something shouldn't be "none" or 0.0 doesn't translate logically into your If condition.
So, this is a proposal for a more robust macro:
Public Sub Macro1()
Dim in_value As Variant
Dim out_value As String
' Adjust the name of the worksheet to your needs'
With Worksheets("Sheet1")
' Read data '
in_value = .Range("A1").Value
' Check what type '
Select Case TypeName(in_value)
Case "Empty"
Let out_value = "Not checked"
Case "String"
If LCase(in_value) <> "none" Then
Let out_value = "checked"
Else
Let out_value = "Not checked"
End If
Case "Integer", "Long", "Single", "Double"
If in_value <> 0 Then
Let out_value = "checked"
Else
Let out_value = "Not checked"
End If
Case Else
Let out_value = "checked"
End Select
' Write data '
Let .Range("A2").Value = out_value
End With
End Sub