How do I make this work? I'm trying to make the code identify the last used cell in column C and go to it. I am having trouble with the last part which is selecting the cell in rng1
Sub jupiter3()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("Belmont")
Set rng1 = ws.Columns("c").Find("*", ws.[c1], xlValues, , xlByRows, xlPrevious)
If Not rng1 Is Nothing Then
MsgBox "last cell is " & rng1.Address(0, 0)
Else
MsgBox ws.Name & " columns A:B are empty", vbCritical
End If
Range("rng1.address(0, 0)").Select
End Sub
the easiest way for me would be to use this one line of code
Sheets("Belmont").Range("C" & Sheets("Belmont").Range("C" & Rows.Count).End(xlUp).Row).Select
but if you want to modify yours then
Sub jupiter3()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("Belmont")
Set rng1 = ws.Columns("c").Find("*", ws.[c1], xlValues, , xlByRows, xlPrevious)
If Not rng1 Is Nothing Then
MsgBox "last cell is " & rng1.Address(0, 0)
rng1.Select
Else
MsgBox ws.Name & " columns A:B are empty", vbCritical
End If
End Sub
Changing Range("rng1.address(0, 0)").Select to rng1.Select or Range(rng1.address).Select
The rng1 variable is defined as a range which is interpreted by the language in a way in which it doesn't fit into range().select You want to define a string variable and do it like this.
replace Range("rng.address(0,0)").Select with
Dim zen as String
zen=rng.address(0,0)
range(zen).select
Related
[1
I wrote =sum(A2:A11) in cell A1, and I wrote random numbers in A2:A11. Then I deleted some rows and then the A1 cell's range changed automatically. But I don't understand why the range does not change automatically when I add new rows and intert new values. How can I make it change automatically? Do I have to use vba to do this?
A Worksheet Change Event: Monitor Change in Column's Data
I personally would go with JvdV's suggestion in the comments.
On each manual change of a cell, e.g. in column A, it will check the formula
=SUM(A2:ALastRow) in cell A1 and if it is not correct it will overwrite it with the correct one.
You can use this for multiple non-adjacent columns e.g. "A,C:D,E".
Nothing needs to be run. Just copy the code into the appropriate sheet module e.g. Sheet1 and exit the Visual Basic Editor.
Sheet Module e.g. Sheet1 (not Standard Module e.g. Module1)
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
UpdateFirstRowFormula Target, "A"
End Sub
Private Sub UpdateFirstRowFormula( _
ByVal Target As Range, _
ByVal ColumnList As String)
On Error GoTo ClearError
Dim ws As Worksheet: Set ws = Target.Worksheet
Dim Cols() As String: Cols = Split(ColumnList, ",")
Application.EnableEvents = False
Dim irg As Range, arg As Range, crg As Range, lCell As Range
Dim n As Long
Dim Formula As String
For n = 0 To UBound(Cols)
With ws.Columns(Cols(n))
With .Resize(.Rows.Count - 1).Offset(1)
Set irg = Intersect(.Cells, Target.EntireColumn)
End With
End With
If Not irg Is Nothing Then
For Each arg In irg.Areas
For Each crg In arg.Columns
Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
If Not lCell Is Nothing Then
Formula = "=SUM(" & crg.Cells(1).Address(0, 0) & ":" _
& lCell.Address(0, 0) & ")"
With crg.Cells(1).Offset(-1)
If .Formula <> Formula Then .Formula = Formula
End With
End If
Next crg
Next arg
Set irg = Nothing
End If
Next n
SafeExit:
If Not Application.EnableEvents Then Application.EnableEvents = True
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume SafeExit
End Sub
Use a nested function as below:
=SUM(OFFSET(A2,,,COUNTA(A2:A26)))
I want to find where 'price tag' is on the sheet, and follow that column to select all way down.
I have wrote
Range(Cells.Find("Price tag"), Range(Cells.Find("Price Tag")).End(xlDown))
but I got [range method of object _global failed] message.
What is wrong with the code, and how can I fix it?
Using the Find Method
If the searched value is not found, the result will be Nothing, so it is safest to use a range variable with the Find method, and then test the variable against Nothing.
Option Explicit
Sub Test()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim ColumnRange As Range
Dim fCell As Range ' simplified due to assuming it is never in cell `A1`
Set fCell = ws.Cells.Find("Price Tag", , xlFormulas, xlWhole, xlByRows)
' Decide what to do if found or not.
If fCell Is Nothing Then
MsgBox "'Price Tag' not found.", vbCritical
Exit Sub
Else
Set ColumnRange = ws.Range(fCell, fCell.End(xlDown))
MsgBox "'Price Tag' was found in cell '" & fCell.Address(0, 0) _
& "' and the address of your range is '" _
& ColumnRange.Address(0, 0) & "'.", vbInformation
End If
' But usually you know in which row...
With ws.Rows(1)
Set fCell = .Find("Price Tag", .Cells(.Cells.Count), xlFormulas, xlWhole)
End With
' or in which column it is:
With ws.Columns("A")
Set fCell = .Find("Price Tag", .Cells(.Cells.Count), xlFormulas, xlWhole)
End With
End Sub
This function will extend the selections for you.
Public Function DataCells(Source As Range) As Range
Dim ColUsedRange As Range
Dim Col As Range
Dim RowCount As Long
For Each Col In Source.Columns
Set ColUsedRange = Range(Col, Col.EntireColumn.Cells(Source.Parent.Rows.Count).End(xlUp))
If RowCount < ColUsedRange.Rows.Count Then RowCount = ColUsedRange.Rows.Count
Next
Set DataCells = Source.Resize(RowCount)
End Function
Usage
Sub Test()
Dim Target As Range
Set Target = Cells.Find("Price tag")
If Not Target Is Nothing Then
Set Target = DataCells(Target)
Application.Goto Target
End If
End Sub
I want to search a range A1-A99 in a certain sheet (wsCaseinfo) for the word Overview. I get a 1004 error on the 'with' line.
The code is part of a larger code using 3 different sheets in 2 different files. Code cycles through 100 files, so something efficient would be appreciated. Many thanks for your help.
With wsCaseinfo.Range(Cells(1, 1), Cells(99, 1))
Set cellx = .Find(what:="Overview", LookAt:=xlPart)
End With
You need to append the Cells() with the parent sheet:
With wsCaseinfo.Range(wsCaseinfo.Cells(1, 1), wsCaseinfo.Cells(99, 1))
Other wise the Cells() will refer to the active sheet and not the same sheet as the Range().
You can also nest a With in the first With
With wsCaseinfo
With .Range(.Cells(1, 1), .Cells(99, 1))
Set cellx = .Find(what:="Overview", LookAt:=xlPart)
End With
End With
With Sheets("wsCaseinfo").Range(Sheets("wsCaseinfo").Cells(1, 1), Sheets("wsCaseinfo").Cells(99, 1))
Set cellx = .Find(What:="Overview", LookAt:=xlPart)
End With
Three Four ways of referring to a sheet:
The name (as above)
The index (eg. Sheets(4))
The codename (eg. Sheet4)
Using a variable eg.
Dim MySheet As Worksheet
Set MySheet = ThisWorkbook.Worksheets("Sheet4")
then using
MySheet.Cells()
If you use Cells(), you must qualify. Instead:
Sub luxation()
Dim cellx As Range, wsCaseinfo As Worksheet
Set wsCaseinfo = Sheets("Sheet1")
With wsCaseinfo.Range("A1:A99")
Set cellx = .Find(what:="Overview", LookAt:=xlPart)
MsgBox cellx.Address
End With
End Sub
Change the Set statement to suit your needs.
Find in Worksheet
Shortest
With wsCaseInfo
Set cellx = .Range("A1:A99").Find("Overview", , xlValues, xlPart)
End With
Short
With wsCaseInfo
Set cellx = .Range("A1:A99").Find("Overview", , xlValues, xlPart)
If Not cellx Is Nothing Then
Debug.Print cellx.Address
Else
Debug.Print "Cell range not found."
End If
End With
Long
Sub FindInWorksheet()
Const cSheet As String = "Sheet1"
Dim wsCaseInfo As Worksheet
Dim cellx As Range
Set wsCaseInfo = ActiveWorkbook.Worksheets(cSheet)
With wsCaseInfo
' Full
'Set cellx = .Range("A1:A99").Find("Overview", .Range("A99"), _
xlValues, xlPart, xlByColumns, xlNext, False)
' Preferable
'Set cellx = .Range("A1:A99").Find("Overview", , _
xlValues, xlPart, xlByColumns)
' Minimal
Set cellx = .Range("A1:A99").Find("Overview", , xlValues, xlPart)
If Not cellx Is Nothing Then
Debug.Print cellx.Address
Else
Debug.Print "Cell range not found."
End If
End With
End Sub
Find Method Reminder
The 1st argument, What, contains the data to search for and is required. All other arguments are optional.
By omitting the second argument, After, your search starts from
A2 and ends with A1 which is often preferable because we have
headers in the first row. But to start the search from A1 and end
with A99, you would have to set the After parameter to "A99".
The 3rd, 4th and 5th arguments, LookIn, LookAt and
SearchOrder, are SAVED each time a Find is 'performed'.
By setting the LookIn argument's parameter to xlValues you prevent possible
searching in formulas (or comments).
LookAt is correctly set to xlPart to find values of the What parameter (Overview) in cells where it is only a part of them e.g. Product Overview or Overview of Parts will be found. Or is it?
SearchOrder can safely be omitted, since we're searching in a one-column range.
The 6th argument, SearchDirection, is by default xlNext which
is used in the code and can therefore be safely omitted.
The 7th argument, MatchCase, is by default False to find OverView or ovErView which is probably no issue here.
You could try:
EDITED VERSION
Option Explicit
Sub test()
Dim rngToSearch As Range
Dim Result As Range
Set rngToSearch = wsCaseinfo.Range("A1:A99")
Set Result = rngToSearch.Find(What:="Overview", LookIn:=xlValues, LookAt:=xlWhole)
If Not Result Is Nothing Then
MsgBox "The word ""Overview"" appears in:" _
& vbNewLine & "Row " & Result.Row _
& vbNewLine & "Column " & Result.Column _
& vbNewLine & "Address " & Result.Address
Else
MsgBox "The word ""Overview"" does not exist in range " & rngToSearch.Address & "."
End If
End Sub
I need to search a date in a column and if not found stop the macro. The date comes from a Cell
Dim rng1 As Range
Dim strSearch As String
strSearch = Worksheets("Calculations").Cells(4, 3).Value
MyInput.Activate
Set rng1 = Range("H:H").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
'Macro follows
Else
MsgBox "Date not found"
End If
End Sub
What this macro does is always returns the message box even if date is there.
Thanks
you're trying to look for a date as a string type.
I just changed the strSearch to dteSearch with a Date type.
Dim rng1 As Range
Dim dteSearch As Date
dteSearch = Worksheets("Calculations").Cells(4, 3).Value
MyInput.Activate
Set rng1 = Range("H:H").Find(dteSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
'Macro follows
Else
MsgBox "Date not found"
End If
End Sub
Good luck!
I'm creating an excel file with column A to H are mandatory cells.
This excel file will be passing around for input.
So, I would like to highlight the empty cells as a reminder.
I have written the following code...
Sub Highlight_Cell()
Dim Rng As Range
For Each Rng In Range("A2:H20")
If Rng.Value = "" Then
Rng.Interior.ColorIndex = 6 ‘yellow
Else
Rng.Interior.ColorIndex = 0 'blank
End If
Next Rng
MsgBox "Please fill in all mandatory fields highlighted in yellow."
End Sub
However, I would like to set the range from A2 to the last row that contains data within column A to H.
Also, display the message box only when empty cell exist.
Could you please advise how should I amend?
Million Thanks!!!
This is a VBA solution that prevents the user from saving until the desired range is filled (acknowledging Gserg's comment that that the last row is one that has at least one cell entered)
In the second portion you can either add your sheet index directly, Set ws = Sheets(x) for position x, or Set ws = Sheets("YourSheet") for a specific sheet name
The code will only highlight truly blank cells within A to H of this sheet till the last entered cell (using SpecialCells as a shortcut). Any such cells will be selected by the code on exit
Put this code in the ThisWorkbook module (so it fires whenever the user tries to close the file)
Private Sub Workbook_BeforeClose(Cancel As Boolean)
bCheck = False
Call CheckCode
If bCheck Then Cancel = True
End Sub
Put this code in a standard module
Public bCheck As Boolean
Sub CheckCode()
Dim ws As Worksheet
Dim rng1 As Range
Dim rng2 As Range
bCheck = False
'works on sheet 1, change as needed
Set ws = Sheets(1)
Set rng1 = ws.Columns("A:H").Find("*", ws.[a1], xlValues, xlWhole, xlByRows)
If rng1 Is Nothing Then
MsgBox "No Cells in columns A:H on " & ws.Name & " file will now close", vbCritical
Exit Sub
End If
Set rng2 = ws.Range(ws.[a1], ws.Cells(rng1.Row, "H"))
On Error Resume Next
Set rng2 = rng2.SpecialCells(xlBlanks)
On Error GoTo 0
If rng2 Is Nothing Then Exit Sub
bCheck = True
rng2.Interior.Color = vbYellow
MsgBox "Please fill in all mandatory fields on " & ws.Name & " highlighted in yellow", vbCritical, "Save Cancelled!"
Application.Goto rng2.Cells(1)
End Sub