How do i add + 1 to activecell in vba - vba

I am kept on getting run time 13 error. all i am trying to do add 1 to activecell.
dim rang as range
rang = activecell + 1
msgbox rang

You're not setting the rang reference.
Set rang = ActiveCell
One problem down.
You're relying on implicit conversions and default properties, which makes it much harder than it needs to be, to understand what's going on.
rang.Value = CLng(ActiveCell.Value) + 1
MsgBox rang.Value
If that blows up with a runtime error 13, then ActiveCell.Value isn't an integer value. You can't legally add +1 to a String... Or do anything (including mere comparison) with an error value. Use IsError to determine if the cell contains a value you can work with, before you work with it:
If Not IsError(rang.Value) Then
MsgBox rang.Value
End If

You want to reference the active cell's value, like this
rang = ActiveCell.Value + 1
Edit - Runtime error 13 is a type mismatch, basically you are trying to combine incompatible data types (assuming the active cell contains a number, not a number formatted as text). Try this.
Dim rang as Integer
rang = ActiveCell.Value + 1
msgbox rang
You can convert numbers formatted as text to numeric values by copying a cell with a one in it, then paste special, and select multiply (assuming the content is valid as a number)

Sub addOne()
ActiveCell = ActiveCell.Value + 1
End Sub
Try This. This will simply add 1 in current value. Make sure its not a string value in active cell. Hope This help.

Related

Checking the data type (integer or string) in a word table

I am trying to do some conditional formatting in word table based on the value in a specific cell.
If the value is <1 set the background to green; if the value is between 1 and 10, format the background yellow and if the value is above 10 format the background red.
I am able to loop through a table and debug.print the content of each cell but am struggling with checking for the datatype in the correspoding cell.
I tried IsNumeric, Int, Fix but none work
`
Sub ConditionalFormat()
Dim tbl As Table, r As Long, c As Long
Set tbl = ActiveDocument.Tables(1)
For r = 1 To tbl.Rows.Count
For c = 1 To tbl.Columns.Count
If tbl.Cell(r, c) = Int(tbl.Cell(r, c)) Then
tbl.Cell(r, c).Shading.BackgroundPatternColor = wdColorBlueGray
End If
Next c
Next r
End Sub
where am i going wrong?
`
Word tables have "end of cell" characters that can get in the way when you process a cell's content.
In your case,
Int(tbl.Cell(r,c))
won't work because tbl.Cell(r,c) returns the Cell, not its value or content. To get its content, you really need
tbl.Cell(r.c).Range
But even that just specifies a block of material in the cell, so it might contain text, images etc. What you are typically looking for is the plain text of the cell, which is really
tbl.Cell(r.c).Range.Text
So you might hope that, for example, if your cell contained the text "42" the expression
IsNumber(tbl.Cell(r.c).Range.Text)
would return True. But it doesn't, because each Word table cell has an end-of-cell character that is returned at the end of the .Range.Text, and that means VBA does not recognise the text as Numeric. To deal with that, you can use
Dim rng As Word.Range
Set rng = tbl.Cell(r.c).Range
rng.End = rng.End - 1
Debug.Print IsNumber(rng.Text)
Set rng = Nothing
SOme VBA functions will ignore the end-of-cell marker anyway as they are intended to be reasonably flexible about how to recognise a number, e.g. you should be able to use
Val(tbl.Cell(r,c).Range.Text)
without running into problems.
As for which functions to use to test/convert the value, that really depends on how much you can assume about your data, how much validation you need to do and what you need to do with your data.
In a nutshell, Val looks for "bare numbers", e.g. 123, 123.45, and numbers in scientific notation. If it finds something non-numeric it will return 0. AFAICR Int and Fix work in similar ways but modify the number in different ways. IsNumeric, CInt, CDbl and so on recognise numbers taking account of the Regional Settings in your OS (e.g. Windows) and accepts/ignores grouping digits (e.g. so they might recognize 1,234,567.89 and even 1,,234,567.89 as 1234567.89 on a typical US system and 1.234.567,89 as the "same number" on a German system). CInt etc. will raise an error if they don't recognise a number.
Anything more than that and you'll probably have to find or write a piece of code that does exactly what you need. I expect there are thousands of such routines out there.
Probably worth noting that the Range objects in Excel and Word have different members. Excel has a Range.Value property but Word does not.
Try:
Sub ConditionalFormat()
Dim r As Long, c As Long
With ActiveDocument.Tables(1)
For r = 1 To .Rows.Count
For c = 1 To .Columns.Count
With .Cell(r, c)
Select Case Val(Split(.Range.Text, vbCr)(0))
Case Is < 1: .Shading.BackgroundPatternColor = wdColorGreen
Case Is > 10: .Shading.BackgroundPatternColor = wdColorRed
Case Else: .Shading.BackgroundPatternColor = wdColorYellow
End Select
End With
Next c
Next r
End With
End Sub

Dynamic Named Range with Moving Data Below

I am trying to create a dynamic named range that I can use for a data validation list. I use these all time but in this case I have information that is housed below the range that cannot be counted in the range. Also, I have a macro that insert rows within this range that do need to be counted.
I normally would use something like this if nothing else was in the column: =OFFSET($A$1,0,0,COUNTA($A:$A),1)
I need to start this one down the page a little ways so I used:
=OFFSET($A$24,0,0,COUNTA($A$24:$A24),1)
Notice I have removed the "$" before the last "24" in the formula hoping it would expand accordingly, but that does not seem to be consistent.
Basically, I need the COUNTA range to only include a range of cells that will always be growing and shrinking.
I'm not bad in VBA and am open to a solution that might include looping through a range of cells and stopping once it reaches a cell that's value equals a certain text string (in the case in would be .Value = "Request 1"). But I am a little apprehensive about feeding a form or ActiveX Control, as this has caused me issues in the past with viewing and printing functionality.
I used a the following code to create a range elsewhere in the workbook that I could then easily use to create a dynamic named range:
Sub UpdateEntities()
Dim i As Long, x As Long
i = 24
x = 1
Sheets("Values").Range("AH:AH").ClearContents
Do While Cells(i, 1).Value <> "REQUEST 1"
Cells(i, 1).Select
If ActiveCell.Value <> "" Then
Sheets("Values").Cells(x, 34).Value = ActiveCell.Value
i = i + 1
x = x + 1
Else
i = i + 1
End If
Loop
End Sub

VBA How to Check if Cell Value is valid and exists?

I have this cell.Offset(0, -2) cell that I need to check if it exists inside my VBA loop.
My idea is that if the cell has an .Offset(0, -2) that does not exist (e.g. say cell = Column B and cell.Offset(0, -2) = Column A-1, cell.Offset(0, -2) is supposed to be invalid), I want to be able to check that it doesn't exist in the if else statement.
Right now when it doesn't exist, I'm getting a “Runtime Error 1004: Application defined or object defined error”.
I've tried IsErr(cell.Offset(0, -2)), cell.Offset(0, -2).Value, If cell.Offset(0, -2) Is Nothing Then, cell.Offset(0, -2) = "", but none of them seem to work... can anyone point me in the right direction? I'm pretty new to VBA and it seems like different variable types have different ways of checking if the value exists.
If you can use your offset amount as a variable, or some method to evaluate against the cell's column, you don't need to defend against errors. Consider below...
Sub IsvalidARea()
Dim OffsetAmount As Integer: OffsetAmount = -2
Dim Cell As Range
If Cell.Column + OffsetAmount < 1 Then
MsgBox "Oh FALSE!"
Else
'EVERYTHING IS OKAY!
End If
End Sub
A solution for this is by using the constantly misused On Error Resume Next, coupled with a If IsError. Here's an example:
On Error Resume Next
If IsError(ActiveCell.Offset(, -2).Select) = True Then
'This is indicative of an error. Meaning you are on Column B, and you ran out of space.
Else
'This means an error did not occur. Meaning you were at least on Column C or above.
End If
There may be a better solution, in fact I am sure there is. But what this will do is allow you to move past the actual 1004 Application error, and you can actually identify, and use the error that was really returned, instead of just forcing your macro/script to end.
To avoid using the error check, you can always check the current column index (B is 2) and make sure whatever you are offsetting by, once subtracted by your index is greater than 0. For example, column B is 2. Your offset is 2. 2 - 2 = 0, so it should not attempt it. Column C is 3, 3 - 2 = 1, which is greater than 0 so it would be valid. Both are explorable methods.

Excel VBA - How to validate input to be in certain column

I have a script that asks for a starting cell
Set myCell = Application.InputBox( _
prompt:="Choose a starting field", Type:=8)
If myCell = Null Or myCell = "" Or Len(myCell.Value) < 3 Or Len(myCell.Value) > 12 Then
MsgBox "Incorrect cell value"
Exit Sub
Else
So, I have these checks for the value of the given cell so the script will not run if the validation does not go through. What I need is also for the validation to check whether the cell in certain column (D in my case).
So I need the validation to say "IS the selected cell in column D?" If Yes, continue, if no stop.
I've relentlessly googled to try to find this kind of comparison but I just fail to give it a good query.
Any help is appreciated. Thanks
With the help of Rich Holton I found the solution.
In order to check whether the input cell is in the column you want it to the following syntax can be used:
If myCell.Column <> 4 Then
...
End If
Where 4 is equal to Column D in this case. (Column A = 1, Column B = 2 and so on...)

VBA Run Time Error 13 Type Mismatch #VALUE

In some of my column's cells there appear #VALUE! words and formulas inside are as follows example:
=IF(VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))=1;1;1+INDIRECT(ADDRESS(329;COLUMN();;;VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))-1)))
Mentioned column is CT. Now when i am trying to loop through the cells when it comes to first occurence of #VALUE! i get an error:
Run Time Error 13, Type mismatch on this line:
L = 9
Do While Cells(L, "CT").Value <> "" '<========= HERE AN ERROR
L = L + 8
Loop
How to fix that?
Cells doesn't take any String parameter, the type mismatch error you're getting has nothing to do with #VALUE / the data being processed - because the code never gets to evaluate the data, since Cells wants two Integer parameters: dang this bites me everytime - apparently you can use string parameters in the Cells function. Ugh.
So the problem is with comparing the value to "" - a string. #VALUE! isn't a valid string function so you need to account for it:
Dim theCell As Range
Set theCell = Cells(L, "CT")
If Not IsError(theCell.Value) Then
Do While Not IsEmpty(theCell.Value)
'...
L = L + 8
Loop
End If
You might also want to correctly qualify that function call:
Do While Not IsEmpty(ActiveSheet.Cells(L, "CT").Value)
That way it's explicit that you're looking at a cell in the active worksheet; an unqualified call is implicitly doing that, and anything implicit is potentially confusing and bug-prone.
Make sure the top of the module says Option Explicit and that L is properly declared:
Dim L As Long
"L" being a meaningless identifier, you should consider naming it after what you're using it for:
Dim currentRow As Long
currentRow = 9
Do While Not IsEmpty(ActiveSheet.Cells(currentRow, "CT"))
That way your code becomes much easier to read, follow and understand.