Identifying cells that are empty or showing #REF! error in a given range - excel

My code is not working properly. It's only showing the first empty cell T10 but cells from T10 to T15 are all empty. I would also like to identify cells that are showing #REF! in them. I don't need the address of empty cells (as there could be quite a few on bigger scale) but would like to know the address of cells with #REF! Thank you!
Sub Identiycells()
Dim Cancel As Boolean
Dim cell As Range
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets(Array("a", "b"))
For Each cell In sh.Range("T6:T18")
If IsEmpty(cell) 'Or showing #REF! Then
MsgBox "Data Missing or Formula error" & cell.Address
Application.Goto cell, True
Cancel = True
Exit For
End If
Next cell
Next sh
End Sub

You could collect the errors in a String and only report once at the end. For checking #REF or other errors you can test with IsError(cell.value).
As you are going through different sheets, it might be good to specify which sheet the cells are on. You can get a cell reference including its sheet with Split(cell.address(External:=True), "]")(1).
Suggested code:
Sub Identiycells()
Dim Cancel As Boolean
Dim cell As Range
Dim sh As Worksheet
Dim report as String ' collect all errors
Dim errorMsg as String ' error for current cell
Dim errorCell as Range ' cell to focus at the end
For Each sh In ThisWorkbook.Worksheets(Array("a", "b"))
For Each cell In sh.Range("T6:T18")
errorMsg = ""
If IsEmpty(cell) Then
errorMsg = "Data Missing"
If errorCell Is Nothing Then Set errorCell = cell
ElseIf IsError(cell.value) Then
errorMsg = "Invalid Reference"
Set errorCell = cell
End If
If errorMsg <> "" Then
report = report & errorMsg & " in " & _
Split(cell.address(External:=True), "]")(1) & vbCrLf
End If
Next cell
Next sh
If Not errorCell Is Nothing Then
MsgBox report
Application.Goto errorCell, True
Cancel = True
End If
End Sub

Related

Add a text to an existing cell

I'm trying to create a function in VBA to add a text to an existing cell.
, 
I want to add "Brand" to cells in the first column. I want to use this function in any cell where I enter the formula.
I'm very new to VBA. I tried searching the internet but couldn't find a simple solution for my level. Could anyone please help me with this? 
Thank you
Add a new module in the Visual Basic Editor (VBE).
Add this code to the module:
Option Explicit
Public Sub Add_Brand()
Dim Cell As Range
For Each Cell In Selection
Cell = "Brand " & Cell
Next Cell
End Sub
Select a range of cells, go to View > Macros on the toolbar and run the Add_Brand macro.
Edit: I should add that if the selected range of cells contain a formula then this will overwrite the formula with the new value.
Edit 2: If you did have formula (not an array formula) I guess you could use this code....
Public Sub Add_Brand()
Dim Cell As Range
For Each Cell In Selection
If Cell.HasFormula Then
Cell.Formula2 = "=""Brand "" & " & Mid(Cell.Formula2, 2, Len(Cell.Formula2))
Else
Cell = "Brand " & Cell
End If
Next Cell
End Sub
A Worksheet Change: Add a Prefix
The following code needs to be copied to the sheet module of the worksheet where it is meant to be applied e.g. Sheet1 (not in a standard module e.g. Module1 nor in the ThisWorkbook module).
It runs automatically: whatever you attempt to write to A2:A1048576 gets the "Brand " prefix.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const FIRST_CELL As String = "A2"
Const PREFIX As String = "Brand "
On Error GoTo ClearError
Dim trg As Range
With Me.Range(FIRST_CELL)
Set trg = .Resize(Me.Rows.Count - .Row + 1)
End With
Dim irg As Range: Set irg = Intersect(trg, Target)
If irg Is Nothing Then Exit Sub
Dim pLen As Long: pLen = Len(PREFIX)
Dim iCell As Range, iString As String
Application.EnableEvents = False
For Each iCell In irg.Cells
iString = CStr(iCell.Value)
If Len(iString) > 0 Then
'If InStr(1, iString, PREFIX, vbTextCompare) <> 1 Then
iCell.Value = PREFIX & iString
'End If
End If
Next iCell
ProcExit:
On Error Resume Next
If Not Application.EnableEvents Then Application.EnableEvents = True
On Error GoTo 0
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
Resume ProcExit
End Sub
Select the first cell you want to change before running the code.
Sub insertBrand()
Do While ActiveCell.Value <> ""
ActiveCell.Value = "Brand " & ActiveCell.Value
Cells(ActiveCell.Row + 1, ActiveCell.Column).Activate
Loop
End Sub

How to add blank rows below selected cell and keep formatting and formulas of above

Sub addRows()
' Adds new blank lines based on user input, keeping formatting and formulas of above.
Dim numRows As Long
Dim raSource As Range
Dim bResult As Boolean
Set raSource = ActiveCell.EntireRow
numRows = InputBox("Enter number of rows to insert. Rows will be added above the highlighted row.")
On Error Resume Next
raSource.Copy
bResult = Range(raSource.Offset(1, 0), raSource.Offset(numRows,
0)).EntireRow.Insert(Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove)
Application.CutCopyMode = False
If Not bResult Then
MsgBox "Inserting rows failed!", vbExclamation
End If
End Sub
The code works how I want it to except it keeps all the data from the selected row and pastes it to new rows. I want to only keep the formatting and formulas of the selected row and insert the new row below.
Try this code. I have linkedan example workbook as well. Let me know if this works.
Download example workbook here
Sub insertXRows()
Dim cell As Range
Dim lngRows As Long
Application.ScreenUpdating = False
'ERROR HANDLER
On Error GoTo ErrMsg
'#CHECK IF ACTIVE CELL IS IN A TABLE
'SOURCE: https://stackoverflow.com/a/34077874/10807836
Dim r As Range
Dim lo As ListObject
Set r = ActiveCell
Set lo = r.ListObject
If Not lo Is Nothing Then
Select Case lo.Name
Case "Table1"
If r.Row = lo.Range.Row Then
MsgBox "In Table1 Header"
Else
MsgBox "In Table1 Body"
End If
Case "SomeOtherTable"
'...
End Select
Else
MsgBox "Active cell is not in any table. Please select a cell in an active table and retry."
Exit Sub
End If
'MSGBOX to enter #rows to insert
lngRows = InputBox("Enter number of rows to insert. Rows will be added above the highlighted row.")
'CODE TO INSERT X Rows
Selection.Resize(lngRows).EntireRow.Insert
For Each cell In Intersect(ActiveSheet.UsedRange, Selection.Offset(-1, 0).EntireRow)
If cell.HasFormula Then
cell.Copy cell.Offset(1, 0)
End If
Next
Application.ScreenUpdating = True
'ERROR MSG
On Error GoTo 0
Exit Sub
ErrMsg: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure insertX, line " & Erl & "."
End Sub

Press a button to sum a range of cells

In column (T2) going down I have the category "money spent". In the next column (U2) I have the date "mm/dd/yy". I want to take the money spent between two dates, sum them up and display it in a message box. How do I do this?
My code so far is:
Sub Button()
Dim myRange
Dim Results
Dim Run As Long
myRange = Worksheet("sheet1").Range ("T2", "5")
Results = WorksheetFunction.Sum(myrange)
MsgBox (Results)
End Sub
This will prompt you for two single cell date selections, and then offset to get the total. This is assuming the dates you select are in Column U so it can add up values in Column T. If you are planning on entering dates into another cell you will need to use find or something to do get the range.
If you want to use a button just assign the Sub.
Option Explicit
Sub CalculateTotal()
Dim startrange As Range
Dim endrange As Range
On Error GoTo errhandler
Dim dateselected As Boolean
dateselected = False
'Make sure one date per range is selected
Do Until dateselected = True
Set startrange = Application.InputBox("Please Enter Single Cell Starting Date Range", , , , , , , 8)
Set endrange = Application.InputBox("Please Enter Single Cell Ending Date Range", , , , , , , 8)
If IsDate(startrange.Value) And IsDate(endrange.Value) Then
dateselected = True
End If
Loop
With ActiveSheet
Dim daterange As Range
Set daterange = .Range(startrange, endrange) 'Combine Ranges
Dim cell As Range
Dim total As Double
total = 0
For Each cell In daterange.Offset(0, -1)
total = total + cell.Value ' Get Total
Next cell
MsgBox "Total value of daterange: " & total
End With
Exit Sub
errhandler:
Select Case Err.Number
Case 424 ' Add in other cases as needed
MsgBox "Range selection cancelled, Exiting"
Exit Sub
Case Else
MsgBox "Unhandled error: " & Err.Number & vbNewLine & Err.Description
Exit Sub
End Select
End Sub

Go to matching cell in a row range based on drop down list

I have a list of names in a row, A2 to AAS2, I also have a drop-down list containing all of those names. I would like some VBA code that when the list is changed excel jumps to the cell matching the item in the list. Could someone please help me with this? Thank you.
The names are just text, no named ranges.
Here is what I have tried so far:
Private Sub FindTicker()
Dim MyVariable As String
MyVariable = Range("L1").Value
Application.Goto Reference:=Range(MyVariable)
End Sub
And Also
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address <> [L1].Address Then
Exit Sub
Else
JumpToCell
End If
End Sub
Sub JumpToCell()
Dim xRg, yRg As Range
Dim strAddress As String
strAddress = ""
Set yRg = Range("A2:AAS2")
For Each xRg In yRg
'MsgBox Cell.Value
If xRg.Value = ActiveCell.Value Then
strAddress = xRg.Address
End If
Next
If strAddress = "" Then
MsgBox "The Day You Selected in Cell D4 Was Not Found On " & ActiveSheet.Name, _
vbInformation, "Ticker Finder"
Exit Sub
Else
Range(strAddress).Offset(0, 1).Select
End If
End Sub
When I tried using both of these when I changed the drop-down list nothing happened. No errors or anything.
Lots of ways to do this and with some tweaks your code above could work but its a bit inefficient and more complicated than it needs to be. The simplest way would be to use the Find method of the Range class to locate the cell:
Lets say your drop-down list of names is in cell A1 on sheet MySheet and the long list is in column C. Use the Find method to set a range variable to equal the first cell containing the item in cell A1.
Dim rng As Range
Dim ws As Worksheet
Set ws = Sheets("MySheet")
Set rng = ws.Range("C:C").Cells.Find(ws.Range("A1"), lookat:=xlWhole)
If Not rng Is Nothing Then ' the item was found
rng.Select
Else
MsgBox "This item is not in the list", vbInformation
End If

vba#excel_highlight the empty cells

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

Resources