Find and select a string - vba

I want to find the string "P1" in worksheet Sheet1 for a macro I am making. I can't seem to find how to do this after searching for a while. Anything that was suggested didn't work. Anyone know how to achieve this?

Just use the Find() function:
Dim r As Range
Set r = Sheet1.Cells.Find(What:="P1")
If Not r Is Nothing Then
r.Select
MsgBox "First found at " & r.Address
End If

Related

Is it possible in VBA to write an invalid formula to a range?

I have the following code in a VBA macro:
Option Explicit
Sub WriteFormula()
Dim rng As Range
Set rng = Range("A1:B2")
' Works
rng.Formula = "=ROUNDUP(1, 1)"
' Doesn't work
rng.Formula = "=ROUNDUP(1)"
End Sub
The second write contains an invalid formula and causes a runtime exception:
Is there any way to disable error checking so that the second write succeeds?
No, you cannot bypass error control and write the bad formula but you could change the formula to text and write the text. This would give you the opportunity to view what was attempted to be written and correct it on the worksheet before applying the modifications to the VBA code.
Option Explicit
Sub WriteFormula()
Dim str As String
Dim rng As Range
Set rng = Range("A1:B2")
On Error GoTo forceWriteText
' Doesn't work
str = "=ROUNDUP(1)"
rng.Formula = str
Exit Sub
forceWriteText:
rng.Value = Chr(39) & str
End Sub
A bit tricky, but you could write your 'wrong' formula as a string in one cell, then, in another cell, use the hidden evaluate function (see https://stackoverflow.com/a/4472470/78522)
Well, cheeky answer.
Option Explicit
Sub WriteFormula()
Dim rng As Range
Set rng = Range("A1:B2")
' Works
rng.Formula = "=ROUNDUP(1, 1)"
' Doesn't work
rng = "'=ROUNDUP(1)"
End Sub
The Second formula is wrong syntax, = Round(number,num_digits) so its throws an error. Either remove it or correct it.
Thank You.
If you want to avoid the error for second line then you use "On Error Resume Next" statement. First statement will be succeed.

Run time error 13 on For loop

I am trying to use a combobox in my user interface, but if none of the options are good for the user they can type it in but after if they have entered something I want to save it so next time it appears in the list. I have tried the following approach:
For i = Range("O3") To Range("O3").End(xlDown)
If Not i.Value = ComboType.Value Then
Range("O3").End(xlDown) = ComboType.Value
End If
Next i
But this gives the above error on the first line. I am not very familiar with For loops in VBA so I am hoping somebody can help me.
This is how to make the for-each loop from O3 to the last cell with value after O3:
Public Sub TestMe()
Dim myCell As Range
Dim ws As Worksheet
Set ws = Worsheets(1)
With ws
For Each myCell In .Range("O3", .Range("O3").End(xlDown))
Debug.Print myCell.Address
Next myCell
End with
End Sub
It is a good practise to declare the worksheet as well, because otherwise you will always work with the ActiveSheet of the ActiveWorkbook.

Targetting a Range With Dynamic Row Reference Based On Search

I'm real new to VBA coding and have been doing alright but I have now hit a wall with my final (and probably more complex than it needs to be) macro of the worksheet. I've been trying to make it work all weekend through multiple google searches and using various answers from stackoverflow's other questions to compile my own script, but to no avail. This is what I have so far (apologies coders, I know this will look like it was written by a 3 year-old):
Sub Build_Delete()
Dim rngA As Range
Dim cell As Range
Set rngA = Worksheets("Database").Range("D9:D177").End(xlUp)
For Each cell In rngA
If cell.Value = Range("A2").Value Then
cell.Select
Range("D" & ActiveCell.Row & ":AB" & ActiveCell.Row).Select
Selection.Delete
End If
Next cell
End Sub
The above works, no errors are returned, however it doesn't do anything noticeable.
I'm aware this is most likely atrocious, so this is what I am trying to do:
Database!D9:D177 contains the titles for a set of data in columns D to AB (4 to 28) .
There is an ActiveX Search Box that populates cell Database!A2 in real time with whatever is searched (eg. "Test" typed into Search Box, "Test" appears in cell Database!A2).
When I run the macro, I want it to check range Database!D9:D177 for the text string found in Database!A2, then delete the contents of columns D to AB for that row (eg. A2 = "test", Found "test" in cell D21, Delete D21:AB21).
The row is a dynamic value which is what is throwing me mostly with this, but the columns are fixed.
Also, the button for the macro is located on a separate worksheet (Front Page!), but the script will run solely on the Database! page.
Only needs to work in excel, not open office.
Only other thing I can think of that is relevant is that the cells can be left blank after deletion, they do not need to be filled, and the worksheet will never need to be printed so margins aren't an issue.
Optionally I would like to add an "Are You Sure? 'Yes' 'No' Msgbox at the start of the script, but I can play with that later as I know I am pushing my luck with this.
Any help would be greatly appreciated!
I always find it faster to use FIND rather than check the value of each cell.
If you want to find all values in case of duplicates you can go on to use .FINDNEXT(rFound) - https://msdn.microsoft.com/en-us/library/office/ff839746.aspx
Public Sub Build_Delete()
Dim rngA As Range
Dim rFound As Range
Dim wrkSht As Worksheet
Set wrkSht = ThisWorkbook.Worksheets("Database")
Set rngA = wrkSht.Range("D9:D177")
With rngA
Set rFound = .Find(wrkSht.Range("A2"), LookIn:=xlValues, LookAt:=xlWhole)
If Not rFound Is Nothing Then
If MsgBox(rFound.Value & " found on row " & rFound.Row & "." & vbCr & _
"Delete?", vbInformation + vbYesNo) = vbYes Then
rFound.EntireRow.Delete Shift:=xlUp
End If
End If
End With
End Sub

Declaring an excel formula as a constant in vba

I received some help on here to declare a formula as a constant in vba. I have approximately ten formulas that are all similar variations on a theme. I've set 9 of them and they work fine the below one throws up a Run-time error (Run-time error '1004'; Application-defined or object-defined error.
Option Explicit
Public Const csFORMULA = "=CONCATENATE(""AVABIS"",IF(I2=0,"""",CONCATENATE(UPPER(AlphaNumericOnly(LEFT(I2,3))),UPPER(AlphaNumericOnly(RIGHT(I2,3))))),IF(O2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(O2,""0"","""")))),IF(R2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(R2,""0"","""")))),IF(W2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(W2,""0"","")))),IF(AB2=0,"""",AlphaNumericOnly(SUBSTITUTE(AB2,""0"",""""))),IF(AC2=0,"""",AlphaNumericOnly(SUBSTITUTE(AC2,""0"",""""))),IF(AD2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AD2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AF2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AF2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AH2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AH2,""-"",""X""),""."",""Y""),""0"",""Z""))))"
Sub AvivaBIS()
Dim lr As Long
Dim cl As Range
Dim rng As Range
Dim mssg As String
Dim ws As Worksheet
Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
lr = .Range("I" & Rows.Count).End(xlUp).Row
'add the formula to generate the unique key
Range("B2:B" & lr).Formula = csFORMULA
Range("B2:B" & lr) = Range("B2:B" & lr).Value
End With
Set rng = Nothing
Set ws = Nothing
Application.ScreenUpdating = True
End Sub
I've deleted the other non-essential code from the above to simplify my question.
Steps I've taken so far:
Tried pasting the original formula straight in the sheet - this works.
Tried replacing the declared formula as something simple (e.g. A1+A2) - this works.
Double checked the quotation marks to see I have the right number - these seem fine.
Copied another very similar formula from the others I've created - this works also.
Any suggestions on what else I could look at to fix this would be gratefully received. Is there a way to get more information when it throws up a run-time error?
Thanks as always for taking the time to look.
You missed doubling up on one set of empty string double quotes (just after W2 about midway through the formula) and had an extra closing bracket at the end.
Public Const csFORMULA = "=CONCATENATE(""AVABIS"",IF(I2=0,"""",CONCATENATE(UPPER(AlphaNumericOnly(LEFT(I2,3))),UPPER(AlphaNumericOnly(RIGHT(I2,3))))),IF(O2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(O2,""0"","""")))),IF(R2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(R2,""0"","""")))),IF(W2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(W2,""0"","""")))),IF(AB2=0,"""",AlphaNumericOnly(SUBSTITUTE(AB2,""0"",""""))),IF(AC2=0,"""",AlphaNumericOnly(SUBSTITUTE(AC2,""0"",""""))),IF(AD2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AD2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AF2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AF2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AH2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AH2,""-"",""X""),""."",""Y""),""0"",""Z"")))"

Excel 2010 VBA How to lookup a value in multiple sheets?

I have an excel file with 14 worksheets, i need to lookup for a value in different columns of each sheet, and if its found, return the name of the sheet where the value was found in a list on a summary sheet.
I have tried with if and vlookup function but i can´t find a proper result, also i tried with pivot table but since i have multiple sheets its not working for me.
I am hoping that somebody helps me with a bit of VBA coding to solve this issue.
I am very newbie at coding and VBA and still i don´t understand all of it, so i haven´t tried to code myself, sorry for that.
Try using the following formula functions to create a solution. If you can't come up with something that works, post what you have and we can work through it.
ADDRESS(row_num, column_num, [abs_num], [a1], [sheet_text])
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
IF(logical_test,value_if_true,value_if_false)
Also consider using Named Ranges
Let me know what you come up with :)
Hope this helps. :)
Sub findStuff()
Dim ws As Worksheet
Dim strWhat As String
Dim rngSearch As Range
Dim rngFound As String
Dim i As Integer
strWhat = "Raspberry"
For Each ws In Worksheets
Set rngSearch = ws.Cells.Find(What:=strWhat)
If Not rngSearch Is Nothing Then
i = i + 1
If i = 1 Then
rngFound = rngSearch.Worksheet.Name
Else
rngFound = rngFound & ", " & rngSearch.Worksheet.Name
End If
End If
Next ws
MsgBox "'" & strWhat & "' found on the following worksheet(s): " & rngFound & "."
End Sub