“Run-time error ‘13’: Type mismatch” error message - vba

Good afternoon.
I’m new at VBA. From my research on the internet, I’ve been able to add some lines that display a message box when an NG is entered into a cell within the range. However, when I try to delete the inputs from several cells, I get a Run-time error ‘13’: Type mismatch message. Any ideas what I’m doing wrong and how to fix it? I’ve added the code that I put in VBA below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("I3:JY30")) Is Nothing Then Exit Sub
If Target.Value <> "NG" Then Exit Sub
MsgBox "ATTENTION: If bell cup is No Good, please replace with new cup and notify supervisor/leader for review. Also, document bell cup serial number and concern on worksheet titled Scrap Bell Tracking "
End Sub
Also, when I click Debug, the If Target.Value <> "NG" Then is highlighted.
Thank you in advance for your help.

Target is a Range, and hence it may consist of more than one cell. In that case, the Value property is invalid.
A simple solution would be to ignore changes with more than one cell: For that, we need to add the following before the access to the Value property:
If Target.Count <> 1 Then Exit Sub
But that would not show a message if e. g. the user pastes five cells, and one or more of them contain the text. The perfect solution would be looping through the range and check each cell separately. And then you would have to think if you want to show the message more than one time if the text is found in more than one cell. So, I will leave that as an exercise to the reader...

Related

If-Then statement Looping

I have created an If-Then statement code that will open up a Message Box if there would be a duplicate.
My Problem is that when there is a duplicate, i cannot exit the Message Box. It's like it is in a loop.
My code here is:
Private Sub Worksheet_Change(ByVal Target As Range)
If Sheets("IELTS Passed").Range("O1").Value = "True" Then
MsgBox "This Applicant already exist!"
End If
By the way, the Range("O1") contains the formula which will look for any duplicates within the sheet "IELTS Passed".
Any help would greatly be appreciated!
Well, a certainly good option is running the If-Then part only when a change is happening in the cells which have a modifying effect on this O1 cell.
Use the target argument for that:
If Not Application.Intersect(Target, RangeWhichAffectsThisCell) is Nothing Then
‘Your code comes here
End if
Another way:
At the end of your code, remove the applicant entry (wherever its cell is) which caused the MessageBox to pop up. I assume this sets the O1 cell to “False”.
But, we do not know all the details so we canot give you a 100% accurate answer.

Incorrect target range in Worksheet_Change event

I am an Excel-VBA newcomer and I am trying to write a short piece of code which is triggered by somebody changing the value of cells in a worksheet. It should set the value of the changed cell to zero if it's less than zero. The code looks like this:
Private Sub Worksheet_Change(ByVal Target As Range)
'Debug.Print Target.Address
If Target.Column = 6 Then
For Each Cell In Target.SpecialCells(xlCellTypeConstants, 3)
If Cell.Value < 0 Then
Cell.Value = 0
End If
Next
End If
End Sub
Now what happens is that when I change the value of any cell in column 6, every cell in the sheet containing numbers less than zero is also changed to zero.
I was thinking that the "Target" Object that is created for the Worksheet_Change event handler would only contain the cell/cells changed, and thus my code would only change the value of cells that were modified and triggered the event in the first place.
I tried to help myself by using Debug.Print to output the address of the object. It printed out the address of every cell in the sheet with a value less than zero, so I assume the handler ran several times.
I actually found a workaround for the problem itself but my questions are these: how did I fail in using the Worksheet_Change event and what can I do in the future to not have such problems?
EDIT 1: Updated code with bug fix suggested in comments
EDIT 2: Updated code with error handling to deal with Array Formulae
In answer to your question
[1] how did I fail in using the Worksheet_Change event and [2] what can I do in the future to not have such problems?
Technically you didn't
Nothing for this type of problem, although the following rule helps in general
You are correct in your understanding of the Targetobject. Your code failed because SpecialCells doesn't like a single cell to operate on. Give it one and it expands it to the entire sheet! Give it anything else and it works just fine.
The reason your Debug.Print displays all the cells is that every time your code changes a cell, another change event is triggered. Luckily for you the second one finds a zero so it doesn't trigger another one. The following general rule should help avoid a lot of problems, just not this particular one:
Always surround any code in an event handler that changes any part of the workbook with Application.EnableEvents.
To fix you code so it works, simply remove the SpecialCells method call. Since you are using Cell.Value instead of the highly recommended Cell.Value2 (see here), VBA implicit type converts numbers formatted as text to actual numbers for you. Thus the code works both on numeric and text values.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
'Debug.Print Target.Address;
Application.EnableEvents = False
For Each Cell In Target '.SpecialCells(xlCellTypeConstants, 3)
If Cell.Column = 6 And Cell.Value < 0 Then
On Error GoTo Error:
Cell.Value = 0
On Error GoTo 0
End If
Next
GoTo ExitSub:
Error:
If Err.Number = 1004 Then ' 1004 -> "You cannot change part of an array."
'Application.Undo ' Uncomment to disallow array entering a negative value formula into/across column 6
MsgBox "A cell could not be zeroed as" & vbCr & "it is part of an array formula.", vbExclamation, "Microsoft Office Excel"
On Error GoTo 0
Else
On Error GoTo 0
Resume
End If
ExitSub:
Application.EnableEvents = True
End Sub
Notes:
- Update 1: Code now correctly deals with multi-cell changes.
- Update 2: Code now traps error 1004 to deal with entering Array Formulae. It can either allow the array formula to be entered resulting in negative values in column 6, or stop the entry altogether.
This works (Updated)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range
For Each c In Target
If c.Column = 6 Then If IsNumeric(c) Then If c < 0 Then c = 0
Next c
End Sub
And please, learn and use OPTION EXPLICIT !
I came here looking for a way to stop my worksheet from "flashing" as it ran code to format columns and rows, due to users changing data anywhere in the sheet, including Filters and Sorting.
Aside, from the official answer to the OP's problem, If you're trying to control the Worksheet_Change() event from firing at all (it will still fire but you can bypass it), in circumstances where you want users to change data for example, but not areas around the data, such as fields or labels as part of your VBA system, I use the Target.Row element to determine my limits. Combined with Target.Column, and you can hone-in on specific cells that are free for the user to control.
i.e.
Dim myTopLimit AS Integer
myTopLimit = 6
etc..etc
if Target.Row < myTopLimit and Target.Row > myBottomLimit and Target.Column < myLeftLimit and Target.Column > myRightLimit then
.... code to allow WorkSheet_Change() to do somthing
else
.... code to force WorkSheet_Change() to drop through or no code
End If

how do I change the position of my image with coordinate ranges in vba

I'm trying to program a Chess-Game in VBA. I'd like to change the position of the figures with mousemove. I can already move them but It would be great if I could release the figure and the figure so jumped into the middle of the field.
I have no Idea how do solve the Problem
Thanks in advance
PS: Sorry for my bad english
Best case scenario - use the macro recorder. Copy the figure and paste it somewhere.
See the code. Then make sure that it works, only in the given range of the chessboard. Then make an event like this:
Option Explicit
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("A1:H8")) Is Nothing Then Exit Sub
Debug.Print Target.Address
End Sub
And try to build the recorded code in Target.Address. The event is for the right click of the mouse. It should be put in the Worksheet part of the VBEditor.

VBA Compile Error: Invalid Outside Procedure

I'm trying to create and run a pretty simple macro in Excel 2016, but I keep getting the following error message "Compile Error: Invalid Outside Procedure.
All the macro is trying to do is when I click a button on one worksheet, the macro moves to another worksheet, and amends a filter on a particular column (and removes the zero's from the column).
I've recorded the macro to do this, but when I assign it to a button and try to run it, the error keeps coming up.
The code shown in the VBA tab is as follows:
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
Can someone help as it's driving me nuts!
Thank you
Half code (or incomplete code) is like half-truth, difficult to understand or judge. So, if I understand your question here's the (probable) solution.
1. On the button click method, write the sheet change code (e.g. Sheets("books").Select)
2. Once the intended sheet is selected, select the column you want to apply filter on by simply recording the macro.
3. Then do the rest of the tasks.
These are simple steps. If you still don't succeed then please revert.
It could be just as easy as deleting the first 'End Sub' in your code.
w1n5rx seems to be correct with completing your code to perfom what you're describing.
But maybe other options to try:
Maybe try the active controlx button <--- or however its labeled.
or try
Static Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub

Can I find whether a Cell in Excel is referenced in a formula?

I have searched alot of sites on the internet, and I'm guessing I haven't found an answer because it is not possible, to try to understand the following:
I would like to understand if a Cell containing a value (say 10) plays into / forms part of a formula further into the document. I KNOW that the cell I have is NOT a formula cell, it is a single entry, however, I am trying to understand if this cell forms part of a formula. The need for this is there are ALOT of formulas and ALOT of data, and I am trying to see which data is relvant and which data is not.
Hope somone can help?
Kind regards
Paul
Manually you can use "Trace Dependents" on the 'Formula Auditing' menu under "Formulas" tool tab.
Using VBA you can check the number of dependents like this:
Range("A1").Dependents.Count
If you want a list of cell addresses that cell A1 is used in you can do this:
MsgBox (Range("A1").Dependents.Address)
I have A1 used in two other cells so my result looks like this:
Full code with error checking:
Sub test()
On Error Resume Next
If Range("A1").Dependents Is Nothing Then
MsgBox ("No dependents found")
Else
MsgBox (Range("A1").Dependents.Address)
End If
End Sub
The Dependents property of a Range object gives you the dependent cells of your formula. Be careful you will get an error if there are no dependent cells
Function hasDependents(r As Range) As Boolean
On Error GoTo err
hasDenpedents = r.Dependents
Exit Function
err:
hasDependents = False
End Function
And then
if hasDependents([A1]) then
'...