How do i clear a specific cell with VBA - vba

I can't finish the last part of my code if anyone could assist. When a cell is not a number I need it to delete the data in the cell.

Try the code below:
Sub ValueOnly()
Dim x As Integer
Application.ScreenUpdating = False
With Sheets("Consolidated Data")
For x = 1 To 3107
With .Cells(10 + x, 9)
If Not IsNumeric(.Value) Then .ClearContents
End With
With .Cells(10 + x, 10)
If Not IsNumeric(.Value) Then .ClearContents
End With
Next x
End With
End Sub

since IsNumeric() can have issues, you may want to try a SpecialCells() approach, which is a little trickier:
Option Explicit
Sub ValueOnly()
Dim numericRng As Range, lastNumericRng As Range, lastRng As Range
Dim iArea As Long
With Sheets("Consolidated Data").Range("I11:I3317").SpecialCells(xlCellTypeConstants) '<--| consider only your wanted range "not blank" values
Set numericRng = .SpecialCells(xlCellTypeConstants, xlNumbers) '<--| store "numeric" values
If Intersect(.Cells(1), numericRng) Is Nothing Then '<--| check if first value is not numeric
.Parent.Range(.Cells(1), numericRng(1).Offset(-1)).ClearContents
End If
With numericRng
For iArea = 2 To .areas.Count '<--| clear all not numeric values between numeric ones
.Parent.Range(.areas(iArea - 1).Offset(.areas(iArea - 1).Count).Resize(1), _
.areas(iArea).Resize(1).Offset(-1)).ClearContents
Next
End With
Set lastRng = .areas(.areas.Count).Cells(.areas(.areas.Count).Count)
If Intersect(lastRng, numericRng) Is Nothing Then '<--| check if last value is not numeric
With numericRng
Set lastNumericRng = .areas(.areas.Count).Offset(.areas(.areas.Count).Count).Resize(1)
End With
.Parent.Range(lastNumericRng, lastRng).ClearContents
End If
End With
End Sub

Related

VBA Highlight row if cell value is numeric

I am trying to highlight rows in Excel if they have a numeric values in this column (others are blank), however this code highlights all of them:
For lRow = LastRow To FirstRow Step -1
With .Cells(lRow, "AF")
If IsNumeric(.Value) Then
.EntireRow.Interior.Color = 5296274
End If
End With
Next lRow
Any advice or assistance will be appreciated.
The safest way to check for Numeric values in a cell is also check that the cell is not empty, or contains only spaces, for that you can use Trim(.Value2) <> "".
Code
If IsNumeric(.Value) And Trim(.Value2) <> "" Then
.EntireRow.Interior.Color = 5296274
End If
Edit 1: Faster run-time code.
Using VBA, the tasks which consume the longest are the ones accessing the worksheet, in this case it's .EntireRow.Interior.Color = 5296274.
What we can do, is use a Range object, in my code it's ColorRng, and every time the If criteria is met, we add that cell to this Range, using the Union function. At the end of the code, we just change the color of the EntireRow in ColorRng, which will result coloring the entire rows which are not numeric at one shot.
Modified Code
Option Explicit
Sub ColorEmptyRows()
Dim ColorRng As Range
For lRow = LastRow To FirstRow Step -1
With .Cells(lRow, "AF")
If IsNumeric(.Value) And Trim(.Value2) <> "" Then
If Not ColorRng Is Nothing Then
Set ColorRng = Application.Union(ColorRng, .Cells(lRow, "AF"))
Else
Set ColorRng = .Cells(lRow, "AF")
End If
End If
End With
Next lRow
' if the range has at least 1 cell, color the entire range at the same time
If Not ColorRng Is Nothing Then ColorRng.EntireRow.Interior.Color = 5296274
End Sub
Empty cells are also considered as numeric with that function. You can use If Isnumeric(.Value) and .Value <> "" Then for instance.

VBA loop through range and output if complete range is empty

I have searched a lot about my question but could not find the answer I need.
I have a table A1:DT97138. Within this table I want to check per row, starting from cell B2 to DT2 if all the cells in one row are empty. Then output "Empty" or "Not Empty" in the next cell, DU2. Then do the same for row 3, 4 etc to 97138 (and output the same results row per row in DU2, DU3 etc).
I found out how to do this for 1 specific row, as you can see below, but I cannot find out how to iterate trough the whole range, row by row.
Sub rowEmpty()
Dim rng As Range, r As Range
Set rng = Range("B2:DT97138")
If WorksheetFunction.CountA(Range("B2:DT2")) = 0 Then
Cells(2, 125) = "Empty"
Else
Cells(2, 125) = "Not Empty"
End If
End Sub
Thanks for your help!
Your are doing well. Just need to loop thru the range like this.
Sub rowEmpty()
Dim rng As Range, r As Range
Set rng = Range("B2:DT97138")
For Each r In rng.Rows
If WorksheetFunction.CountA(r) = 0 Then
Cells(r.Row, 125) = "Empty"
Else
Cells(r.Row, 125) = "Not Empty"
End If
Next r
End Sub
Enter your formula at once in the last column:
With Range("DU2:DU97138")
.Formula = "=IF(COUNTA(B2:DT2)=0,""Empty"",""Not Empty"")"
'then eventually convert it to constants
.Value = .Value
End With
No loops, simpler, probably much faster :-)

How to delete a specific value in a column with vba

I want to delete a specific value in a column with vba.
Here is my code for now. But of course it is not working.
vstd = Range("J6").Offset(l - 1, 0).Value
For Each Rng2 In Range("F6:F2555")
If Rng2.Value = vstd Then
Rng2.ClearContents
End If
Next
Is this close to what you're looking for?
Sub Macro2()
Dim vSpecificVal As Variant
vSpecificVal = Range("J6").Offset(l - 1, 0).Value
Call Range("F6:F2555").Replace(vSpecificVal, "")
End Sub
Please let us know thanks
here's an AutoFilter() approach:
Option Explicit
Sub ClearColumn()
Dim l As Long
l = 1 '<--| initializing 'l' variable value
With Range("F5:F2555") '<--| reference your range
.AutoFilter Field:=1, Criteria1:=Range("J6").Offset(l - 1, 0).Value '<--| filter on value in cell offsetted "l-1" rows from J6
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Offset(1).Resize(.Rows.count - 1).SpecialCells(xlCellTypeVisible).ClearContents '<--| if any filtered cell found clear their contents
End With
ActiveSheet.AutoFilterMode = False
End Sub
be sure that you initialize l values so as not to have Range("J6").Offset(l - 1, 0) reference an invalid Range (i.e. l must be less than 6)

Iterating through a range until you find different value in VBA

I'm trying to create a VBA function that starts from the bottom of a range, and returns the first value that's different from the value at the bottom.
Example:
In the above table, I'd like to be able to grab the last value in the "Month" column (11), and iterate to the top until the value 10 is reached, and return that value.
I just started looking into VBA 3 days ago and am very unfamiliar with the language so I'm still trying to grok the syntax.
I have no doubt that my thinking is fuzzy with this, so I'd really appreciate feedback on my errors.
Here's what I have right now:
Code:
Function NextValue(num1 As Range)
For c = num1.End(xlDown) To num1.Item(1)
If Cells(c, 1) <> num1.End(xlDown) Then
NextValue = Cells(c, 1)
Exit For
End If
Next c
End Function
In case it's not clear, here's a description of what I'm trying to do, line-by-line.
1). Initiate a For-Loop that begins at the end of a range and decrements to the top
2). Check if that cell does not match the last value in that column
3). If it does not, then set the value of the function to that value
4). Terminate If statements, For loops, and end the function.
Your help is greatly appreciated.
Try this:
Function NextValue(num1 As Range) as Integer
Dim y As Integer
'get the last cell from num1
Set num1 = num1.End(xlDown)
y = -1
Do Until num1.Offset(y, 0).Value <> num1.Value
y = y - 1
Loop
'set function return to the different cell
NextValue = num1.Offset(y, 0).value
End Function
This will handle both compact ranges and disjoint ranges:
Option Explicit
Public Function SomethingElse(rng As Range) As Variant
Dim r As Range, values() As Variant
Dim i As Long, strvalue As Variant
ReDim values(1 To rng.Count)
i = 1
For Each r In rng
values(i) = r.Value
i = i + 1
Next r
strvalue = values(rng.Count)
For i = rng.Count To 1 Step -1
If values(i) <> strvalue Then
SomethingElse = values(i)
Exit Function
End If
Next i
SomethingElse = CVErr(xlErrNA)
End Function
Not clear to me if you want an UDF or a code to be used in a macro
in the first case you've already been given answers
in the latter case you may want to consider these two options:
Public Function FirstDifferent(rng As Range) As Variant
With rng.Parent.UsedRange
With Intersect(.Resize(, 1).Offset(, .Columns.Count), rng.EntireRow)
.Value = rng.Value
.RemoveDuplicates Array(1)
FirstDifferent = .Cells(.Rows.Count, 1).End(xlUp).Offset(-1).Value
If FirstDifferent = .Cells(.Rows.Count, 1) Then FirstDifferent = "#N/A"
.ClearContents
End With
End With
End Function
Public Function FirstDifferent(rng As Range) As Variant
With rng.Resize(, 1)
.AutoFilter Field:=1, Criteria1:=.Cells(.Rows.Count, 1)
FirstDifferent = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Cells(1, 1).Offset(-1).Value ' = 0 '<-- if any rows filtered other than headers one then change their column "B" value to zero
If FirstDifferent = .Cells(.Rows.Count, 1) Then FirstDifferent = "#N/A"
.Parent.AutoFilterMode = False
End With
End Function

Excel VBA - Display next cell if previous cell includes text

I am not a Genius in Excel VBA, so here is my question:
I have an Excel Sheet which has hidden rows.
For example: As long as cell A1 is empty keep the row(A2) hidden. When A1 includes text show the next row (A2).
My Approach was the following:
Sub showRows_Klicken()
Dim rng As Range
For Each rng In Range(Cells(1, 1), Cells(65536, 1).End(xlUp))
If LCase(rng) = "text"
Then
rng.EntireRow.Hidden = False
Else
End If
Next rng
End Sub
I hope somebody can help me out here.
Thanks in advance.
I tried this code. Worked for me. Please give it a try
Sub Macro1()
If Range("A1").Value = vbNullString Then
Columns("B:B").EntireColumn.Hidden = True
ElseIf Not IsEmpty(Range("A1").Value) Then
Columns("B:B").EntireColumn.Hidden = False
End If
End Sub
The Hidden property seems to work. I've changed the function a bit such that it sets the next row (i+1) visible based on row i. It now only checks each 2nd row, otherwise you could hide all rows (if there were nothing), and you would not be able to set any "text" such that the next row is unhidden:
Sub showRows_Klicken()
'loop all rows
For i = 1 To 65536 Step 2
'check if has string "text" and set hidden
If LCase(Cells(i, 1)) = "text" Then
Range(Cells(i + 1, 1), Cells(i + 1, 1)).EntireRow.Hidden = False
Else
Range(Cells(i + 1, 1), Cells(i + 1, 1)).EntireRow.Hidden = True
End If
Next i
End Sub
Thanks for your help, I changed the code a bit and now it works for me:
Sub Schaltfläche259_Klicken()
If Range("A1").Value = vbNullString Then
Rows("2").EntireRow.Hidden = True
ElseIf Not IsEmpty(Range("A1").Value) Then
Rows("2").EntireRow.Hidden = False
End If
End Sub