I'm running the following macro to perform a basic 'FindHighlight' function through a database in MS XL 2003
The find function works perfectly, but the issue I have is that when the 'ClearHighlight' is used (before a search is made) then I get Run-time error 91 - 'Object variable or With block variable not set'
I understand that I need to complete a search before using this function, but others using the tool may not - I was wondering if there is a way to prevent this alert coming up?
(Beginner on VBA!!)
Thank you!
Dim FoundRange As Range
Sub FindHighlight()
Dim tempCell As Range, Found As Range, sTxt As String
sTxt = InputBox("Search string")
If sTxt = "False" Then Exit Sub
Set Found = Range("A1")
Set tempCell = Cells.Find(what:=sTxt, After:=Found, SearchDirection:=xlNext, MatchCase:=False)
If tempCell Is Nothing Then
MsgBox prompt:="Not found", Title:="Finder"
Exit Sub
Else
Set Found = tempCell
Set FoundRange = Found
End If
Do
Set tempCell = Cells.FindNext(After:=Found)
If Found.Row >= tempCell.Row And Found.Column >= tempCell.Column Then Exit Do
Set Found = tempCell
Set FoundRange = Application.Union(FoundRange, Found)
Loop
FoundRange.Interior.ColorIndex = 6
FoundRange.Font.ColorIndex = 3
End Sub
Sub ClearHighlight()
FoundRange.Interior.ColorIndex = xlNone
FoundRange.Font.ColorIndex = xlAutomatic
End Sub
If FoundRange is not set it's value is Nothing so:
Sub ClearHighlight()
if FoundRange is nothing then exit sub
FoundRange.Interior.ColorIndex = xlNone
FoundRange.Font.ColorIndex = xlAutomatic
End Sub
Related
I have a line of code that converts any cells contain #DIV/O error with 0. Which is idealy, apart from when there is no #DIV/o error found in range. When this is that case i get a run time error informing me that there is none found and then I can't move past this.
Is there a way to pass over this issue?
The code goes as follows
Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
For Each rCell In rng
If rCell.Value = CVErr(xlErrDiv0) Then
rCell.Value = 0
End If
Next
I have tried to play around using NullString & For loops but to no avail.
Any help would be greatful.
One way to overcome the issue is to add ErrorHandler like the one below:
Sub DivByZero()
On Error GoTo ErrHandler:
Dim rng As Range
Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
For Each rCell In rng
If rCell.Value = CVErr(xlErrDiv0) Then
rCell.Value = 0
End If
Next
ErrHandler:
If Err.Number = 1004 Then
Exit Sub
End If
End Sub
I am struggling to find out how i can loop through all rows in excel from word. What I want to achieve is that if there is something in the WP column in excel then save the active worddocument with that filename. However i cant figure out something simple as getting the last row(might be empty rows in between), i just get error code 424, which according to MSDN does not give me any real hint whats wrong. Any ideas whats wrong?
Public Sub test()
Dim xlapp As Object
Set xlapp = CreateObject("Excel.Application")
myFileName = "Z:\Dokumentstyring\UnderArbeid\PARTSLIST.xlsm"
xlapp.Workbooks.Open myFileName
xlapp.Application.ScreenUpdating = False
xlapp.Visible = False
a = xlapp.sheets("List").Range("A1").Value
b = firstBlankRow(xlapp)
c = getColumn("WP", xlapp)
xlapp.Application.ScreenUpdating = True
xlapp.ActiveWorkbook.Close (True)
xlapp.Quit
Set xlapp = Nothing
End Sub
My function to receive the last row:
Function firstBlankRow(ByRef xlapp) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
With xlapp.sheets("List")
'~~> Check if there is any data in the sheet
'If xlapp.WorksheetFunction.CountA(.Cells) <> 0 Then
firstBlankRow = .Range("A" & .Rows.Count).End(Excel.XlDirection.xlUp).Row
'Else
firstBlankRow = 1
'End If
End With
End Function
Here is my function for getting the column number
Public Function getColumn(header As String, ByRef xlapp) As Integer
Dim rng1 As Range
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, Columns.Count)).Find(header, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
getColumn = rng1.Column
Else
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End If
End With
End Function
As per our conversation in the comments, change Dim Rng1 As Range to
Dim Rng1 As Object.
You can find the actual values of XlDirection, Xlvalues, xlwhole enums.
Preferably, it's better to do it like this:
Private Const xlUp as long = -4162
'and so on
Edit1:
Here's an adjusted function that solves your problem (I've tested it on my machine)
Public Function getColumn(header As String, ByRef xlapp) As Long
Dim rng1 As Object
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, .Columns.Count))
If rng1 Is Nothing Then
MsgBox ("ERROR: Range object is empty.")
getColumn = -1
Exit Function
End If
For Each m In rng1
If m = "WP" Then
getColumn = m.Column
Exit Function
End If
Next m
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End With
End Function
So I have a contract with information that I wanted to update in different columns...I need to look up this contract in a list of contracts and override specific information with the user inputs.
I tried the code below. I could locate the location of the contract on the list however override doesn't work. Can you please help?
Sub UpdateChargesMacro3()
Dim contract As Double
Dim BR_Reduction As Double
Dim RIA_Reduction As Double
Dim TR_Reduction As Double
Dim PERA_Reduction As Double
Dim TPA_Reduction As Double
Dim JHHH_Reduction As Double
Dim RowCount As Integer
contract = Sheets("Input").Range("C29").Value
JHHH_Reduction = Sheets("Input").Range("C36").Value
Sheets("Final Summary").Select
With ActiveSheet.Range("C:C")
Set uRng = .Find(contract, , xlValues, xlWhole, , MatchCase:=False, searchformat:=False)
If uRng Is Nothing Then
MsgBox Prompt:="Contract not found!", Buttons:=vbInformation, Title:="OK"
End If
Exit Sub
If Not uRng Is Nothing Then
uRng.Activate
RowCount = ActiveCell.Row
Sheets("Final Summary").Range("DJ" & RowCount).value = JHHH_Reduction
End If
End With
End Sub
If uRng Is Nothing Then
MsgBox Prompt:="Contract not found!", Buttons:=vbInformation, Title:="OK"
End If
Exit Sub
Always exits the macro,
move exit inside the if statement
If uRng Is Nothing Then
MsgBox Prompt:="Contract not found!", Buttons:=vbInformation, Title:="OK"
Exit Sub
End If
I am creating macro which will loop through column F and will delete month april from 2013. It seem that the macro is deleting all :-D. I dont know how to set it to delete only my criteria I tried (Month(Now) - 2). Mine date of format looks like DD/MM/YYYY.
Thank you for your help.
Sub Test1()
Dim rgFoundCell As Range
Dim toBeDeted As Range
Dim firstAddress
With Sheets("Sheet1").Range("F:F")
Set rgFoundCell = .Find(What:=(Month(Now) - 2))
If Not rgFoundCell Is Nothing Then
firstAddress = rgFoundCell.Address
Do
If toBeDeted Is Nothing Then
Set toBeDeted = rgFoundCell.EntireRow
Else
Set toBeDeted = Union(toBeDeted, rgFoundCell.EntireRow)
End If
Set rgFoundCell = .FindNext(rgFoundCell)
If rgFoundCell Is Nothing Then Exit Do
Loop While rgFoundCell.Address <> firstAddress
End If
End With
Application.ScreenUpdating = True
If Not toBeDeted Is Nothing Then _
toBeDeted.Delete ' Delete
End Sub
You can't use .Find in the way you think - it is only able to do text match or number match comparisons. This leaves you with having to cycle through each cell in the range and run your comparison explicitly on each cell
Sub Test1()
Dim toBeDeleted As Range
With Sheets("Sheet1").Range("F:F")
For Each c In .Cells
If Month(c.Value) = 3 And Year(c.Value) = 2013 Then
If toBeDeleted Is Nothing Then
Set toBeDeleted = c.EntireRow
Else
Set toBeDeleted = Union(toBeDeleted, c.EntireRow)
End If
End If
Next
End With
If Not toBeDeleted Is Nothing Then _
toBeDeleted.Delete ' Delete
End Sub
You might want to consider running the function on a more refined range than the full F column or use an end of data marker like checking for a blank row to stop the loop.
Try this:
Sub Test1()
On Error GoTo e
Application.ScreenUpdating = False
Dim rng As Range
Dim firstAddress
Set rng = Sheets("Sheet1").Range("F1", Sheets("Sheet1").Range("F1").End(xlDown))
Dim i As Long
i = 1
While i <= rng.Count
If Month(CDate(rng(i))) = 4 And Year(CDate(rng(i))) = 2014 Then
rng (i).EntireRow.Delete
Else
i = i + 1
End If
Wend
x:
Application.ScreenUpdating = True
Exit Sub
e:
MsgBox (Err.Description)
Resume x
End Sub
Maybe try to reduce the F:F range!!!
I'm having a really bad time trying to understand why I get an error which I thing should not appear.
I'm using Office 2007. I have two sheets in Excel, "Ver" and "Encargado", in "Ver" sheet I have one cell in which to put a number and then I press one button. The code inside the button is:
Private Sub CommandButton1_Click()
Dim buscar As Range
dato = Range("b2").Value
If dato = "" Then Exit Sub
Sheets("Encargado").Select
Set buscar = Range("b2:b12").Find(What:=dato, LookIn:=xlFormulas, SearchOrder:=xlByRows)
If Not buscar Is Nothing Then
buscar.Activate
ActiveCell.Offset(, -1).Copy Destination:=Ver.Cells(4, 2)
Sheets("Ver").Select
Else
Sheets("Ver").Select
MsgBox "Encargado no encontrado"
Exit Sub
End If
End Sub
In "Encargado" sheet and inside the range b2:b12 there are only numbers beetwen 101 and 111, and when I put the number 117 as an input (for example) I think it should get into the else part as it shouldn't have found any coincidence, but it gets into the if part, why? and I get an error saying "Error en el método activate de la clase Range" (As you noticed I am using Office in spanish, and programming as well with spanish variables). When I run line by line the error appears in the line "buscar.Activate". Does anyone know where is the error? In the case you want to see it, here is the file: https://www.dropbox.com/s/j1b39fqy971n7lf/Todo.xlsm Thanks.
You have not defined the sheet in find function so its referring ver sheet. Use this code.
Private Sub CommandButton1_Click()
Dim buscar As Range
'Application.ScreenUpdating = False
dato = Range("b2").Value
If dato = "" Then Exit Sub
Set buscar = Sheets("Encargado").Range("b2:b12").Find(What:=dato, LookIn:=xlValues, SearchOrder:=xlByRows)
If Not buscar Is Nothing Then
'Encargado.Cells.Find(What:=Ver.Cells(2, 2), After:=Range("b2"), LookIn:=xlFormulas, SearchOrder:=xlByRows).Select
'desplazamiento en fila, desplazamiento en columna, positivo: hacia abajo, hacia la derecha
'buscar.Activate
c = buscar.Row
Sheets("Encargado").Range("a" & c).Copy
Sheets("Ver").Range("b4").PasteSpecial
Else
Sheets("Ver").Select
MsgBox "Encargado no encontrado"
Exit Sub
End If
'Application.ScreenUpdating = True
End Sub
EDIT: As pointed out in the comments below, the Range object DOES have an .Activate method: http://msdn.microsoft.com/en-us/library/office/ff837085(v=office.15).aspx
buscar is a Range object, which does not have an Activate method. The following should get you where you're going, but out of curiosity -- have you looked into Excel's built-in =VLOOKUP functionality? It might save you from requiring VBA here...
Option Explicit
Private Sub CommandButton1_Click()
Dim TerritorioNum As Long, LastRow As Long
Dim TerritorioRange As Range, FoundRange As Range
Dim VerSheet As Worksheet, EncSheet As Worksheet
'set references up-front
Set VerSheet = ThisWorkbook.Worksheets("Ver")
Set EncSheet = ThisWorkbook.Worksheets("Encargado")
With EncSheet
LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Set TerritorioRange = .Range(.Cells(1, 1), .Cells(LastRow, 2))
End With
TerritorioNum = VerSheet.Cells(2, 2).Value
'find the territory number
Set FoundRange = TerritorioRange.Find(TerritorioNum)
If FoundRange Is Nothing Then
MsgBox ("Encargado no encontrado")
Exit Sub
Else
VerSheet.Cells(4, 2) = EncSheet.Cells(FoundRange.Row, FoundRange.Column - 1).Value
End If
End Sub