VBA: I keep getting an error related to object variable not set properly - excel

I am trying to set this simple code but no matter what I do, I always get an error 'object required' on the line:
Set foundCell = searchRange.Find(What:=searchValue, LookIn:=xlValues)
My source code is as follows:
Option Explicit
'I'm going to let the program search for the date in the pre-filled date -> select the entire row & column below -> move it down by 1 row -> insert the date above the moved pre-filled date -> fill other details
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim submittedDate As Date
Dim searchValue As Variant
Dim searchRange As Variant
Dim foundCell As Range
Set ws = Sheet1 'setting it up so that I'm dealing with Sheet1
ws.Range("A7:A37").NumberFormat = "dd-mmm" 'setting the number format of the values in A7:A37 as dd-mmm
submittedDate = Me.TextBox1.Value 'setting the input value as a variable
searchValue = submittedDate
searchRange = ws.Range("A7:A37")
Set foundCell = searchRange.Find(What:=searchValue, LookIn:=xlValues)
If Not foundCell Is Nothing Then
MsgBox "Value found!"
Else
MsgBox "Value not found..."
End If
End Sub
Any thoughts/help would be appreciated and thank you in advance!
I can't seem to think of anything as a solution, as all the variables are declared ...

The Find() method of the Range class needs a Range object to be called on, while
searchRange = ws.Range("A7:A37")
would result in a searchRange as an array storing the values of the cells "A7:A37", since the default property of the Range object is the Value one (it's as if you had coded searchRange.Value = ws.Range("A7:A37").
While in order to have a Range object you have to use the Set keyword
Set searchRange = ws.Range("A7:A37")
That said, you'd also better declare searchRange as of Range type
Dim searchRange As Range
which would have originated an error for Set searchRange = ws.Range("A7:A37") in the compiling phase, instead of the one you experienced in the runtime one
Finally, you can omit the declaration and use of submittedDate variable and go direct with the searchValue one only
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim searchValue As Variant
Dim searchRange As Range
Dim foundCell As Range
Set ws = Sheet1 'setting it up so that I'm dealing with Sheet1
ws.Range("A7:A37").NumberFormat = "dd-mmm" 'setting the number format of the values in A7:A37 as dd-mmm
searchValue = Me.TextBox1.Value 'setting the input value as a variable
Set searchRange = ws.Range("A7:A37")
Set foundCell = searchRange.Find(What:=searchValue, LookIn:=xlValues)
If Not foundCell Is Nothing Then
MsgBox "Value found!"
Else
MsgBox "Value not found..."
End If
End Sub
A more condensed version of which is the following one:
Private Sub CommandButton1_Click()
Dim foundCell As Range
With Sheet1.Range("A7:A37") ' reference the needed range
.NumberFormat = "dd-mmm" 'setting the number format of the values in referenced range as dd-mmm
Set foundCell = .Find(What:=Me.TextBox1.Value, LookIn:=xlValues) 'search for the TextBox1 value in the referenced range values
End With
If Not foundCell Is Nothing Then
MsgBox "Value found!"
Else
MsgBox "Value not found..."
End If
End Sub

Related

Search range for all cells with specific text and change the value of all adjacent cell to 0

Looking for help to achieve searching a range of cells E9:E with All cells containing "Accommodation & Transportation" and changing the value of the cells adjacent to them with 0. , I was not able to get anything online with similar topic and I'm not too good with VBA coding, though i am able to understand what the code will provide in results.
I Have a Commandbutton1 with the below code :
Sub CommandButton1_click()
Dim blanks As Excel.Range
Set blanks = Range("F9:F" & Cells(Rows.Count, 5).End(xlUp).Row).SpecialCells(xlCellTypeBlanks)
blanks.Value = blanks.Offset(0, -1).Value
End Sub
Further i have a command button that will select only cells that are not blank. I need the above result because if the below code selects Non Blank cells from Columns E:F it wont be selecting cells adjacent to those containing "Accommodation & Transportation" as they are blank cells and it will return the error "Runtime Error '1004' This action wont work on multiple selections".
The below code acts the same as [Go to Special => Constants]
Sub SelectNonBlankCells()
Dim rng As Range
Dim OutRng As Range
Dim InputRng As Range
Dim xTitle As String
On Error Resume Next
xTitle = Application.ActiveWindow.RangeSelection.Address
Set InputRng = Range("E8:F500")
ActiveWindow.ScrollRow = 1
For Each rng In InputRng
If Not rng.Value = "" Then
If OutRng Is Nothing Then
Set OutRng = rng
Else
Set OutRng = Application.Union(OutRng, rng)
End If
End If
Next
If Not (OutRng Is Nothing) Then
OutRng.Select
End If
End Sub
Maybe you can try another approach, if your goal is to edit cells adjacent to certain cells. The code below is based on an example in the Help file of the Range.Find function:
Sub DoSomething()
Dim sh As Worksheet
Set sh = ActiveSheet
Dim checkRange As Range
Set checkRange = sh.Range("E8:F500") ' your intended range to search
Dim foundRange As Range
Set foundRange = checkRange.Find("Accommodation & Transportation")
Dim firstAddr As String
If Not foundRange Is Nothing Then
firstAddr = foundRange.Address
Do
' use foundRange to access adjacent cells with foundRange.Offset(row, col)
'
'
foundRange.Offset(0, 1) = "all good"
Set foundRange = checkRange.FindNext(foundRange)
Loop While Not foundRange Is Nothing And foundRange.Address <> firstAddr
End If
End Sub
Or even better, you could add some parameters to make it more reusable:
Sub Main()
DoSomething "Accommodation & Transportation", ActiveSheet.Range("E8:F500")
End Sub
Sub DoSomething(ByVal findWhat As String, ByVal searchWhere As Range)
Dim foundRange As Range
Set foundRange = searchWhere.Find(findWhat)
Dim firstAddr As String
If Not foundRange Is Nothing Then
firstAddr = foundRange.Address
Do
' use foundRange to access adjacent cells with foundRange.Offset(row, col)
'
'
foundRange.Offset(0, 1) = "all good"
Set foundRange = searchWhere.FindNext(foundRange)
Loop While Not foundRange Is Nothing And foundRange.Address <> firstAddr
End If
End Sub

Selecting element from VBA union

I have a task to make a VBA macro based on few sections in .xls file.
I know that in this file it will always be three sections which starts with specific name in example file "Block". But starting row where "Block" is written each time could be different.
Example of .xls file:
enter image description here
My approach had been to search for address of each column containing string "Block"
And later make further code based on knowing there start of each block are.
My code so far:
Public Values
Sub Macro1()
FindAll ("Block")
Debug.Print Values
'
End Sub
Sub FindAll(text)
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
fnd = text
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
'Find next cell with fnd value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Creates global value with all found adresses
Values = rng.Address
Exit Sub
Output Is received as intended:
$A$5,$A$8,$A$1
However I struggle to select element for further coding.
I tried:
Debug.Print Values.Rows.item(1).Adress
Debug.Print Values.Rows.item(1,1).Adress
Debug.Print Values.Rows.item(1)
Debug.Print Values.Rows.item(1,1)
But it yields "Run-time error '424' "
My desired output would be to create three variables containing addresses for these sections.
That
Debug.Print Section_1
Debug.Print Section_2
Debug.Print Section_3
Would yield:
$A$1
$A$5
$A$8
Is there a way to select nth element from union in VBA?
If you want to access the single cells of the range, you can simply loop over it:
Dim cell as Range
For Each cell In rng
Debug.Print cell.Address
Next
Could also be done using an index:
Dim i As Long
For i = 1 To rng.Count
Debug.Print rng(i).Address
Next
Now in your example, you combine single cells using Union. If you combine larger ranges and want to access those ranges, you can use the Areas-Property. However, Excel will optimize the areas, if you do Union(Range("A1"), Range("A2)), you will end up with one area A1:A2.
With ActiveSheet
Set rng = Union(.Range("D5:E16"), .Range("A1:F12"), .Range("X4"))
End With
Dim a As Range
For Each a In rng.Areas
Debug.Print a.Address
Next
For i = 1 to rng.Areas.Count
Debug.Print rng(i).Address
Next
Btw: Every Range (even a single cell) has the Areas-property set, so it's always safe to loop over the Areas of a range.
Try,
Public Values
Public rngDB() As Range
Sub Macro1()
Dim i As Integer
FindAll ("Block")
Debug.Print Values
For i = LBound(rngDB) To UBound(rngDB)
Debug.Print rngDB(i).Address
Debug.Print rngDB(i).Cells(1).Address
Debug.Print rngDB(i).Cells(1, 2).Address
Debug.Print rngDB(i).Cells(2, 1).Address
Next i
End Sub
Sub FindAll(text)
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
Dim sAddress() As String
Dim n As Integer
fnd = text
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
'GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do
n = n + 1
ReDim Preserve rngDB(1 To n)
ReDim Preserve sAddress(1 To n)
Set rngDB(n) = FoundCell.CurrentRegion
sAddress(n) = rngDB(n).Address
Set FoundCell = myRange.FindNext(after:=FoundCell)
Loop While FoundCell.Address <> FirstFound
'Creates global value with all found adresses
If n Then
Values = Join(sAddress, ",")
End If
End Sub

Find cell(s) with certain text and add hyperlinks in a loop

tldr: Find cell(s) with part number xxxxx and add hyperlink to drawing on server.
We have a spreadsheet containing part numbers across multiple columns & rows. Our requirement is to add a hyperlink to parts' drawing, stored on our server. We have tried highlighting them as a group, but get the error
this can't be done on multiple range selection
We also want to keep the comment information intact, just to complicate it further.
Is there code we can use to search for part number xxxxx & add a hyperlink, then find the next cell and repeat the process?
We have found a "find all" code which highlights the cells, just need some help with the hyperlink issue.
Sub FindAll()
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'What value do you want to find (must be in string form)?
fnd = "70005"
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
'Find next cell with fnd value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Select Cells Containing Find Value
rng.Select
Exit Sub
'Error Handler
NothingFound:
MsgBox "No values were found in this worksheet"
End Sub
Your method can be simplified a bit. My suggestion is to create a function that will add your hyperlinks to any given area.
My test data is
Option Explicit
Sub test()
Dim linkCount As Long
linkCount = AddHyperLinkTo(FindArea:=Sheet1.UsedRange, _
FindThis:="red", _
Link:="https://google.com")
Debug.Print "found: " & linkCount
End Sub
Function AddHyperLinkTo(ByRef FindArea As Range, _
ByVal FindThis As Variant, _
ByVal Link As String) As Long
Dim numberFound As Long
Dim parentWS As Worksheet
Set parentWS = FindArea.Parent
Dim firstFind As Range
Dim findResult As Range
Set findResult = FindArea.Find(What:=FindThis, LookIn:=xlValues)
Set firstFind = findResult
Do Until findResult Is Nothing
parentWS.Hyperlinks.Add Anchor:=findResult, Address:=Link
numberFound = numberFound + 1
Set findResult = FindArea.Find(What:=FindThis, LookIn:=xlValues, After:=findResult)
If findResult.Address = firstFind.Address Then
Exit Do
End If
Loop
AddHyperLinkTo = numberFound
End Function

VBA - how to choose a column containing a specific cell and name it output column?

There is a cell in another worksheet whose value ranges from 1 to 100, I have defined its name as "SpanLength" in the name manager. In the worksheet I am now concerned with, I want to find the cell which contains the same value as "SpanLength", that is, a value from 1 to 100, within the range I have defined as "FindSpanLength". Then I want to call the column that this cell is within "outputcolumn" so that I can use this column further in the script. How can I do this?
The line of code before End Sub causes the error message 'Wrong number of arguments or invalid property assignment'
I am a VBA novice and no doubt my code is fraught with errors, so would appreciate any help I can get. I have already scoured google for answers but haven't found any specific enough for me to understand.
Sub OutputMaximums()
Dim spanlengthcell As Range
Set spanlengthcell = Range("FindSpanLength").Find("SpanLength")
Range("spanlengthcell").Column(1) = outputcolumn
End Sub
New Code, with error message 1004 (Method 'Range' of object '_Worksheet' failed):
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = OUTPUT.Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
When you assign a value to a variable, the variable is on the left hand side of the equals sign.
When using Find always check first that your search term is found before trying to access its properties to avoid subsequent errors.
It is also advisable to specify a number of Find parameters as they may have unexpected settings from when last used on a worksheet.
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
Option Explicit
Sub test()
Dim rngSearch As Range, rngFound As Range
Dim strSearch As String
Dim ColumnNo As Long
strSearch = "Bingo"
With ThisWorkbook.Worksheets("Sheet1")
Set rngSearch = .UsedRange
Set rngFound = rngSearch.Find(strSearch)
If rngFound Is Nothing Then
MsgBox strSearch & " does not excist in range."
Else
ColumnNo = rngFound.Column
MsgBox "Text appears in column " & ColumnNo & "."
End If
End With
End Sub
Sub ShowNamedRange()
'The named Range "SpanLenght" must be on the Sheet "SheetWithNamedRange"!
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Address
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Column
End Sub
and after reading the question again:
Sub SearchRange()
Dim rngSearch As Range
Dim rngFound As Range
Dim strSearch As String
strSearch = Sheets("SheetWithNamedRange").Range("SpanLength").Value
Set rngSearch = Sheets("SheetWithFINDRange").Range("FindSpanLength")
Set rngFound = rngSearch.Find(strSearch)
If Not (rngFound Is Nothing) Then _
MsgBox "Found in column " & rngFound.Column & _
" on the sheet """ & rngFound.Parent.Name & """!"
End Sub

VBA in Excel: Runtime Error 1004

I am trying to do the following. I have several spreadsheets that are named something like "ITT_198763" where the ITT part stays the same but the number changes. I also have one tab called program where the 6 digit number is imported on row 40 (hence the RngToSearch below). I need the program to 1) find the "ITT" sheet for a certain 6 digit number, 2) identify the corresponding row in the "Program" tab, and copy information from the "ITT" tab to row 41 of the identified column. I will be copying more information from the ITT sheet to the specified column, but for now I am just trying to get it to work once.
From the MsgBox, I know it identifies the correct prjNumber (the 6 digit number), but I get the runtime 1004 error on the line Set RngDest. Any help will be appreciated!
Sub Summary_Table()
Dim wks As Worksheet
Dim RngToSearch As Range, RngDest As Range
Dim foundColumn As Variant
Dim prjNumber
For Each wks In ActiveWorkbook.Worksheets
If ((Left(wks.Name, 3) = "ITT")) Then
prjNumber = Right(wks.Name, 6)
MsgBox (prjNumber)
Set RngToSearch = Sheets("Program").Range("C40:q40")
foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch, False)
With Sheets("Program")
Set RngDest = .Range(1, foundColumn) 'Project Name
End With
If Not IsError(foundColumn) Then
wks.Range("E2").Copy RngDest
End If
End If
Next wks
End Sub
I tried the .cell instead with the following code (all else is the same) and now get runtime error 13 on the Set RngDest line:
Set RngToSearch = Sheets("Program").Range("C40:q48")
foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch.Rows(1), False)
With Sheets("Program")
Set RngDest = RngToSearch.Cells(1, foundColumn) 'Project Name
End With
Yuo are getting that error because foundColumn has an invalid value. Step through the code and see what is the value of foundColumn
Here is an example which works.
Sub Sample()
Dim RngDest As Range, RngToSearch As Range
foundColumn = 1
Set RngToSearch = Sheets("Program").Range("C40:q40")
Set RngDest = RngToSearch.Cells(1, foundColumn)
Debug.Print RngDest.Address
End Sub
Add MsgBox foundColumn before the line Set RngDest = RngToSearch.Cells(1, foundColumn) and see what value do you get. I guess the line
foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch, False)
is not giving you the desired value. Here is the way to reproduce the error.
EDIT (Solution)
You need to handle the situation when no match is found. Try something like this
Sub Sample()
Dim RngDest As Range, RngToSearch As Range
Set RngToSearch = Sheets("Program").Range("C40:q40")
foundcolumn = Sheets("Program").Application.Match(1, RngToSearch, False)
If CVErr(foundcolumn) = CVErr(2042) Then
MsgBox "Match Not Found"
Else
Set RngDest = RngToSearch.Cells(1, foundcolumn)
'
'~~> Rest of the code
'
End If
End Sub
You are looking for the Cells function, which has the prototype .Cells([RowIndex], [ColumnIndex]). The Range function takes either a string with a range name (like "A1", or a named range), or other range references.
I figured it out! Found column was the problem. Combining that with the help from the other commenters, the following works:
Sub Summary_Table()
Dim wks As Worksheet
Dim RngToSearch As Range, RngDest As Range
Dim foundColumn As Variant
Dim prjNumber
For Each wks In ActiveWorkbook.Worksheets
If ((Left(wks.Name, 3) = "ITT")) Then
prjNumber = Right(wks.Name, 6)
MsgBox (prjNumber)
Set RngToSearch = Sheets("Program").Range("a40:q48")
foundColumn = Sheets("Program").Rows(40).Find(what:=prjNumber, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False).Column
MsgBox (foundColumn)
With Sheets("Program")
Set RngDest = RngToSearch.Cells(2, foundColumn) 'Project Name
Debug.Print RngDest.Address
End With
If Not IsError(foundColumn) Then
wks.Range("E3").Copy RngDest
End If
End If
Next wks
End Sub

Resources