VBA Macro help need for Excel - vba

Hello I hope this will make sense,
I have found this script that if a letter or number is in one cell it will input a value in the another cell
I was wondering how I could add multiple rules to this.At the moment if C or 9 is entered in a cell then it produces the sentence "word here will show up"
I want it to show up in a different cell not the adjacent one, and also I want to be able to add different letter to the list to output different values.
EG
Cell Has This in Column A Output when Macro runs in Column E
C or 9 "Word0"
HELLO OR GOODBYE "Word1"
Pink or Yellow "Word2"
Etc,
Any help would be great and appreciated as I am very new to VB and Macros.
The code below only does C or 9 I thought I could just add .Forumula to the code below to add more words but it didn't work
Sub CheckValues()
Application.ScreenUpdating = False
With Range("A2", Range("A" & Rows.Count).End(xlUp)).Offset(, 1)
.Formula = "=IF(MIN(FIND({""C"",9},A2&""C9""))<=LEN(A2),""Word0"","""")"
.Value = .Value
End With
Application.ScreenUpdating = True
End Sub

If you're going for a VBA approach then there's no real need to use .Formula. VBA has a Select Case construct that lets you evaluate an expression and carry out a bunch of options based on the outcome of the expression.
Try this:
Sub CheckValues()
Application.ScreenUpdating = False
Dim startRow As Integer
startRow = 2
Dim endRow As Integer
endRow = Range("A2").End(xlDown).row
Dim row As Integer
Dim word As String
For row = startRow To endRow
Select Case Split(Cells(row, 1).Value, " ")(0)
Case "C", "9"
word = "Word0"
Case "HELLO", "GOODBYE"
word = "Word1"
Case "Pink", "Yellow"
word = "Word2"
Case Else
word = ""
End Select
Cells(row, 5).Value = word
Next row
Application.ScreenUpdating = True
End Sub
As you add more options for column a, you only need to repeat the Case *expression* pattern.

Or you could just amend your existing formula and do it without loops:
Sub SO()
With Range("B2:B" & Cells(Rows.Count, 2).End(xlUp).Row).Offset(, 3)
.FormulaR1C1 = "=IFERROR(""Word""&ROUNDDOWN((MATCH(LEFT(RC[-3],SEARCH("" "",RC[-3])-1),{""C"",""9"",""HELLO"",""GOODBYE"",""Pink"",""Yellow""},0)/2)-0.1,0),"""")"
.Value = .Value
End With
End Sub

Related

Filtering depending upon the column values

I have a sheet FC, with this sheet, I have column R, S and T filled.
I would prefer to have a code, which checks if R contains "invalid" and if S and t are filled, then it should filter complete row.
I know we can use isblank function to check whether the cell is blank or not,
but I am struck how I can use a filter function with these condition .Any help will be helpful for me. I am struck how I can proceed with a vba code. Apologize me for not having a code.
You will have to somehow specify last row:
Dim lastRow, i As Long
For i = 1 To lastRow 'specify lastRow variable
If InStr(1, LCase(Range("R" & i).Value), "invalid") > 0 And Range("S" & i).Value = "" And Range("T" & i).Value = "" Then
'do work
End If
Next i
In our If condition we check three things that you asked.
Try this
Sub Demo()
Dim lastRow As Long
Dim cel As Range
With Worksheets("Sheet3") 'change Sheet3 to your data sheet
lastRow = .Cells(.Rows.Count, "R").End(xlUp).Row 'get last row in Column R
For Each cel In .Range("R5:R" & lastRow) 'loop through each cell in range R5 to lase cell in Column R
If cel.Value = "invalid" And Not IsEmpty(cel.Offset(0, 1)) And Not IsEmpty(cel.Offset(0, 2)) Then
cel.EntireRow.Hidden = True 'hide row if condition is satisfied
End If
Next cel
End With
End Sub
EDIT :
To unhide rows.
Sub UnhideRows()
Worksheets("Sheet3").Rows.Hidden = False
End Sub
Assuming Row1 is the header row and your data starts from Row2, in a helper column, place the formula given below.
This formula will return either True or False, then you may filter the helper column with either True or False as per your requirement.
=AND(R2="Invalid",S2<>"",T2<>"")
In case your header row is different, tweak the formula accordingly.
sub myfiltering()
'maybe first row always 4
firstrow=4
'last, maybe R column alaways have any entered info, so let us see what is the last
lastrow=cells(65000,18).end(xlup).row
'go ahead
for myrow=firstrow to lastrow
if cells(myrow,18)="Invalid" and cells(myrow,19)="" and cells(myrow,20)="" then
Rows(myrow).EntireRow.Hidden = True
else
Rows(myrow).EntireRow.Hidden = false
end if
next myrow
msgbox "Filter completed"
end sub
hope this will help you :)
Why you need the vba code for this problem?
Its more simple if you add a new column with if & and formula, and autofiltering within the added col.
The formula may be similar like this in the U2 cell.
=if(and(R2="invalid";S2="";T2="");"x";"")
Also set autofilter to x. :)

Turn flag on/off to change name

I need help.
I have words and numbers in column A3:A500
and I need to change their names.
if a cell contains the word "previ" than put in a new column the letter "p" if the cells is a number. if its a word then dont put "p"
...like turning a flag on and off.
This is what i have:
Sub()
For i=3 to 500
x= range("a:"&i).value
If x contains "previ" Then
prevflag=1
ElseIf x is not integer Then
prevflag=0
End If
If prevflag=1 Then
range("H:"& i )= "p"
End If
Next i
End Sub
Can you guys help me make this work?
and thank you!!
this is what it needs to look like
https://postimg.org/image/e62z4xwlj/
Looking at your example, it looks like you want to put the "p" in rows in a section with a header that contains "previ" but not in a section with a header that doesn't. You also seem to want "p" in rows which have a blank in column A, not just integers. Does the below work for you?
Public Sub addPs()
Dim previFlag As Boolean
Dim c As Range: For Each c In Range("a1:a51")
If InStr(c.Value, "previ") > 0 Then
previFlag = True
ElseIf Not IsNumeric(c.Value) Then
previFlag = False
End If
If IsNumeric(c.Value) Then
If Int(c.Value) = c.Value And previFlag Then c.Offset(0, 3) = "p"
End If
Next c
End Sub
you may be after something like this
Option Explicit
Sub main()
Dim iRow As Long, lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).row
iRow = 3
Do
If InStr(Cells(iRow, 1).Value, "previ") > 0 Then '<--| if current cell contains "previ
iRow = iRow + 1 '<--| then then start scanning for numeric values
Do
If IsNumeric(Cells(iRow, 1).Value) Then Cells(iRow, 3).Value = "p" '<--| if current cell is numeric then write "p" two cells left of it
iRow = iRow + 1
Loop While InStr(Cells(iRow, 1).Value, "Type") = 0 And iRow <= lastRow
Else
iRow = iRow + 1 '<--| else skip to next row
End If
Loop While iRow <= lastRow
End Sub
just change the column offset to your needs (you wrote column "H" but your example has "p"s in column "C")
I did not understand the cases, but still, this is how you check for numeric values:
?isnumeric(6)
True
?isnumeric("test")
False
In your code:
else if not isnumeric(x) then
Does this need to be done with VBA? You could put this formula in H3 and paste it down to H500:
=IF(ISERROR(FIND("previ",A3)),"","p")
However, this doesnt deal with your number criteria, but I don't know what you mean by that. If a cell contains "previ", that cell is not numeric. It may have some numeric digits in it somewhere, but "previ04578" is not a number. Could you share some sample data? Failing that you can check for any numeric digit with stacked substitutions and a length comparison, for example:
=IF(ISERROR(FIND("previ",A3)),"",IF(LEN(A1)=LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A3,"0",""),"9",""),"8",""),"7",""),"6",""),"5",""),"4",""),"3",""),"2",""),"1","")),"p",""))
Another alternative...
Sub FlagRows()
Dim i As Long, val As Variant, bFlag As Boolean: bFlag = False
With Sheets("Sheet1")
For i = 1 To 500
val = .Cells(i, 1).Value
bFlag = IIf(Not IsNumeric(val), IIf(InStr(CStr(val), "previ"), True, False), bFlag)
If IsNumeric(val) And bFlag = True Then .Cells(i, 4).Value = "p"
Next i
End With
End Sub

Excel VBA - How do I refer to a cell's visible content rather than its formula?

I'm trying to loop through a particular range in my Excel spreadsheet(("B13:B65"), to be specific) and hide all rows that have an "X" in them. Something like this:
For i = 13 to 65
If Cells(i, 2) = "x" Or "X" Then Rows(i).RowHeight = 0
Next i
The problem is that I'm getting a type mismatch error.
I assume this is happening because all the cells in this range are formulas rather than text strings. For example, the contents of cell B13 are:
='Monthly'!$C$13
I want my code to evaluate the visible output of the cell, not the actual content.
I get the feeling there's a very easy solution here, but I've been searching for a while with no success. I'm a rookie, obviously...
Based on this example: https://msdn.microsoft.com/en-us/library/office/ff195193.aspx
Sub Main()
For Each c in Worksheets("Sheet1").Range("A1:D10") 'Change for your range
If Lcase(c.Value) = "x" Then
'''Rest of your code
End If
Next c
end sub
You're getting the error because of the OR. There has to be something that can be evaluated to true or false after the Or. Or "X" won't ever be true or false. You need...
If Cells(i, 2) = "x" Or Cells(i, 2) = "X" Then Rows(i).RowHeight = 0
As long as you wanted to use the same code everywhere else.
Use Value property:
If Cells(i, 2).Value = "x"
Loop through static range
Dim rng As Range, c As Range
Set rng = Range("B13:B65")
For Each c In rng.Cells
If UCase(c) = "X" Then
c.EntireRow.Hidden = True
End If
Next c
You could use an AutoFilter
Sub HideEm()
Dim rng1 As Range
Set rng1 = ActiveSheet.Range("$B$1:$B$65")
rng1.Parent.AutoFilterMode = False
rng1.AutoFilter Field:=1, Criteria1:="<>x", Operator:=xlOr, Criteria2:="<>X"
End Sub

Excel VBA - struggling to create macros which takes action on cell values by column

Very new to Excel VBA, and struggling.
I'm a junior C# developer, but am finding that writing simple statements in VBA is very tricky for me. Can anyone tell me how to write VBA code for the following pseudocode requirements please?
Insert True into Column E only WHERE there is a specific string value of X in column A
Insert False into Column E WHERE there is text (ie: something/anything) in column D AND no text (ie: nothing) in Column A
Delete X wherever there is a specific string value X in any cell in Column A.
Any help at all would be so greatly appreciated.
Public Sub Text_Process()
Dim lngLastRow As Long
Dim lngRow As Long
Dim strColA As String
Dim strColD As String
lngLastRow = Sheet1.UsedRange.Rows.Count
For lngRow = 1 To lngLastRow ' change 1 to 2 if you have headings in row 1
strColA = Sheet1.Cells(lngRow, 1).Value ' store value in column A
strColD = Sheet1.Cells(lngRow, 4).Value ' store value of column D
Sheet1.Cells(lngRow, 5).Clear ' clear column E
If strColA = "X" Then ' or whatever you are looking for
Sheet1.Cells(lngRow, 5).Value = True
ElseIf strColA = "" And strColD <> "" Then
Sheet1.Cells(lngRow, 5).Value = False
End If
If strColA = "X" Then ' or whatever you are looking for
Sheet1.Cells(lngRow, 1).Clear ' clear out the value in column A, is this is what is requried?
End If
Next lngRow
End Sub
It's basic stuff do to. VBA has basically the same syntax of VB 6.
You can read the language reference or hitting F1 on VBA editor for help.
Just for example, check this code. Besides your requirements are a bit confusing, pay attention in the code structure and the functions used, like Range.Cells, IsEmpty
Sub Macro1()
Dim limit, index As Integer
' Iterate limit, just for test
limit = 20
' Iterate your worksheet until the limit
For i = 1 To limit Step 1
' Range param is a string, you can do any string contatenation you wish
' Value property is what inside the cell
If (Not IsEmpty(Range("D" & i).Value) And IsEmpty(Range("A" & i).Value)) Then
' Requirement 2
Range("E" & i).Value = False
ElseIf (Range("A" & i).Value = "X") Then
' Requiriment 1
Range("E" & i).Value = True
' Requiriment 3
Range("A" & i).Value = Empty
End If
Next
End Sub
Like Siddharth said, recording a macro and study the generated code is a great way to learn some VBA tricks.

Change a cell's format to boldface if the value is over 500

I am using Excel 2010 and trying to add a bunch of rows placing the sum of columns A and B in column C. If the sum is over 500 I would then like to boldface the number in column C. My code below works works mathematically but will not do the bold formatting. Can someone tell me what I am doing wrong? Thank you.
Public Sub addMyRows()
Dim row As Integer 'creates a variable called 'row'
row = 2 'sets row to 2 b/c first row is a title
Do
Cells(row, 3).Formula = "=A" & row & "+B" & row 'the 3 stands for column C.
If ActiveCell.Value > 500 Then Selection.Font.Bold = True
row = row + 1
'loops until it encounters an empty row
Loop Until Len(Cells(row, 1)) = 0
End Sub
Pure VBA approach:
Public Sub AddMyRows()
Dim LRow As Long
Dim Rng As Range, Cell As Range
LRow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("C2:C" & LRow)
Rng.Formula = "=A2+B2"
For Each Cell In Rng
Cell.Font.Bold = (Cell.Value > 500)
Next Cell
End Sub
Screenshot:
An alternative is conditional formatting.
Hope this helps.
Note: The formula in the block has been edited to reflect #simoco's comment regarding a re-run of the code. This makes the code safer for the times when you need to re-run it. :)