VBA to convert texts to numbers except formula and non-numeric texts - excel

I have a Range("B6:T10000")
Data in the range are a mixture of blanks,#'s ,numbers (formatted as texts), texts and most importantly formulas.
Can someone please help with a VBA macro to:
Find anything that looks like number and convert it to number
Ignore the rest
Don't convert formulas to values
Thank you very much

You can do this without code, or with quicker code avoiding loops
Manual
Copy a blank cell
Select your range B6:T100001
Press F5. Then Goto ... Special
check Constants and then Text
Paste Special Multiply and check Add
This converts text only cells with numbers into numbers, and leaves actual text or formulae alone
Code
Sub Update()
Dim rng1 As Range
On Error Resume Next
Set rng1 = Range("B6:T10000").SpecialCells(xlCellTypeConstants, 2)
On Error Resume Next
If rng1 Is Nothing Then Exit Sub
'presumes last cell in sheet is blank
Cells(Rows.Count, Columns.Count).Copy
rng1.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd
End Sub

here's my version:
Sub Test()
Dim rng as Range, cel as Range
Set rng = Thisworkbook.Sheets("Sheet1").Range("B6:T10000")
For Each cel In rng
If Not IsError(cel.Value) Then _
If Len(cel.Value) <> 0 And cel.HasFormula = False And _
IsNumeric(cel.Value) Then cel.Value = Val(cel.Value)
Next cel
End Sub
I've tested it, and works fine.
Hope this helps.

Give this a try:
Sub Converter()
Dim rBig As Range, r As Range, v As Variant
Set rBig = Range("B6:T10000")
For Each r In rBig
v = r.Value
If v <> "" And r.HasFormula = False Then
If IsNumeric(v) Then
r.Clear
r.Value = v
End If
End If
Next r
End Sub
EDIT#1:
This version ignores errors:
Sub Converter()
Dim rBig As Range, r As Range, v As Variant
Set rBig = Range("B6:T10000")
For Each r In rBig
v = r.Value
If Not IsError(v) Then
If v <> "" And r.HasFormula = False Then
If IsNumeric(v) Then
r.Clear
r.Value = v
End If
End If
End If
Next r
End Sub

ActiveSheet.Range("b5:b6004,h5:h6004").Select
For Each xCell In Selection
If IsNumeric(xCell) = False Then
xCell.Value = Val(xCell.Value)
Else
End If
Next xCell

Related

Change font color for a row of text in cell which contains a certain value

I am writing a check in/out program in excel and have gotten te request that if a line contains "|0|" it should get a different font color.
I've tried with Instr and Cells().Characters but I cannot seem to figure out how to do it.
The cells can have a variety of rows of text. Which is easy enough to solve with splitting them on a return and having a for loop loop, but I cannot seem to figure out how to assign a different font color to a row of text that contains the required value.
Image for illustration of the data:
How do I best solve this?
Added information:
The goal of this is that on button press the whole line of text where the |O| is would be collored differently. Other lines of text that do not have this will remain the same color.
Like in this image as a concept
[]
try this
Public Sub ExampleMainSub()
Dim cell As Range
For Each cell In Selection
If HasMySymbols(cell.Value) Then
WorkWithCellContent cell
Else
cell.Font.ColorIndex = xlAutomatic
cell.Font.TintAndShade = 0
End If
Next cell
End Sub
Private Sub WorkWithCellContent(ByVal cell As Range)
Dim arr As Variant
arr = Split(cell.Value, Chr(10))
Dim firstPosOfRow As Long
firstPosOfRow = 1
Dim subLine As Variant
For Each subLine In arr
If HasMySymbols(subLine) Then
cell.Characters(start:=firstPosOfRow, Length:=Len(subLine)).Font.Color = vbRed
Else
cell.Characters(start:=firstPosOfRow, Length:=Len(subLine)).Font.ColorIndex = xlAutomatic
End If
firstPosOfRow = firstPosOfRow + Len(subLine) + 1 '+1 is needed
Next subLine
End Sub
Private Function HasMySymbols(ByVal somestring As String) As Boolean
HasMySymbols = InStr(1, somestring, "|0|") > 0
End Function
Try this. It works for me.
Sub ChangeRowFontColour()
Dim rng As Range
Dim TextToFind As String
Dim FirstFound As String
TextToFind = "Specific Text"
With ActiveSheet.UsedRange
Set rng = .Cells.Find(TextToFind, LookIn:=xlValues)
If Not rng Is Nothing Then
FirstFound = rng.Address
Do
rng.EntireRow.Font.ColorIndex = 3
For Each part In rng
lenOfPart = Len(part)
lenTextToFind = Len(TextToFind)
For i = 1 To lenOfPart
tempStr = Mid(part, i, lenTextToFind)
If tempStr = TextToFind Then
part.Characters(Start:=i, Length:=lenTextToFind).Font.ColorIndex = 0
End If
Next i
Next
Set rng = .FindNext(rng)
Loop While Not rng Is Nothing And rng.Address <> FirstFound
End If
End With
End Sub

Change "dd.mm.yyyy" to "mm/dd/yyyy" VBA

I know "dd.mm.yyyy" is not formatted as date within Excel, and this conversion part is what is getting to me. I have "31.3.2019" within .cell("C5") and want it to convert within the same cell (replace it) with a new formatting of "3/31/2019". I keep on getting an 'out of range' error and I am not sure where my mistake is.
Below is what I have tried:
Sub DivestitureTemplate_ChangeDateFormat()
Application.ScreenUpdating = False
Dim rng As Range
Dim str() As String
Set rng = Range("C5:C3000")
With Worksheets("Divestiture Template")
For Each rng In Selection
str = Split(rng.Value, ".")
rng.Value = DateSerial(2000 + str(4), str(2), str(0))
Next rng
Selection.NumberFormat = "mm/dd/yyyy"
Application.ScreenUpdating = True
End With
End Sub
Change format of ("C5:C3000") from 31.3.2019 to 3/31/2019 -- it can be continuous, but starting at "C5" as this is an automated report and this is below a specified header. I think I have been looking at this, scripting all day and loosing my head over this for no reason.
To get real dates in the column, try:
Sub DivestitureTemplate_ChangeDateFormat()
Dim cell As Range, rng As Range, d As Date
Set rng = Worksheets("Divestiture Template").Range("C5:C3000")
For Each cell In rng
With cell
arr = Split(.Text, ".")
.Value = DateSerial(arr(2), arr(1), arr(0))
.NumberFormat = "m/dd/yyyy"
End With
Next cell
End Sub
EDIT#1:
Sub DivestitureTemplate_ChangeDateFormat()
Dim cell As Range, rng As Range, d As Date
Dim arr
Set rng = Worksheets("Divestiture Template").Range("C5:C3000")
For Each cell In rng
With cell
arr = Split(.Text, ".")
.Value = DateSerial(arr(2), arr(1), arr(0))
.NumberFormat = "m/dd/yyyy"
End With
Next cell
End Sub

Using VBA to search for a text string in Excel

I'm trying to use VBA in a macro to search for a text string and delete the contents of the column. I previously found this on the website and would like to change it to search columns and delete the text "QA1" while retaining the columns. I hope this makes sense.
LastRow = Cells(Columns.Count, "D").End(xlUp).Row
For i = LastRow To 1 Step -1
If Range("D" & i).Value = "D" Then
Range("D" & i).EntireColumn.Delete
End If
Next i
You want to clear the contents of the whole column if one cell contains QA1?
Sub Test()
Dim rCell As Range
With ThisWorkbook.Worksheets("Sheet1").Columns(4)
Set rCell = .Find("QA1", LookIn:=xlValues)
If Not rCell Is Nothing Then
.ClearContents
End If
End With
End Sub
If you want to just clear each instance of QA1 in column D:
Sub Test()
Dim rCell As Range
With ThisWorkbook.Worksheets("Sheet1").Columns(4)
Set rCell = .Find("QA1", LookIn:=xlValues)
If Not rCell Is Nothing Then
Do
rCell.ClearContents
Set rCell = .FindNext(rCell)
Loop While Not rCell Is Nothing
End If
End With
End Sub
Can it be written to look through the entire worksheet and delete QA1
where ever it is found?
All instances of QA1 on sheet:
Sub Test()
Dim rCell As Range
With ThisWorkbook.Worksheets("Sheet1").Cells
Set rCell = .Find("QA1", LookIn:=xlValues)
If Not rCell Is Nothing Then
Do
rCell.ClearContents
Set rCell = .FindNext(rCell)
Loop While Not rCell Is Nothing
End If
End With
End Sub
Edit: Add LookAt:=xlWhole to the Find arguments so it doesn't delete cells containing QA1 and other text (e.g. QA11 or Some text QA1)
This code goes through columns in a specified row and removes the "QA1" if found
Dim LastColumn As Integer
Dim RowNumber As Integer
Dim i As Integer
LastColumn = UsedRange.SpecialCells(xlCellTypeLastCell).Column
RowNumber = 1 'Adjust to your needs
For i = 1 To LastColumn Step 1
Cells(RowNumber, i).Value = Replace(Cells(RowNumber, i).Value, "QA1", "")
Next i
Loops through the used range of the active worksheet, and removes the selected text.
Sub RemoveText()
Dim c As Range
Dim removeStr As String
removeStr = InputBox("Please enter the text to remove")
For Each c In ActiveSheet.UsedRange
If c.Value = removeStr Then c.Delete
Next c
End Sub

excel Find copy, paste all values that start with 1Z

I am trying to find a script that finds certain values in sheet1 and paste those values in sheet2 A1.
the range is whole sheet1
needs to search all cells for anything that starts with "1Z" and "W"
paste each cell data that starts with "1Z" and "W" in sheet2 under row A.
Currently have this script:
Sub delete_oldads()
Dim cel As Range, cfind As Range
ActiveSheet.UsedRange.Select
For Each cel In Selection
If cel = "" Then GoTo nextcel
Set cfind = cel.Find(what:="1Z", lookat:=xlPart)
If Not cfind Is Nothing Then
cfind.Copy Cells(cfind.Row, "A")
cfind.Clear
End If
nextcel:
Next cel
End Sub
But this one copy/paste all the matching cells in the same sheet and also if a match is found in the same row, it will copy the last one only.
This does not use FIND() and may be a little slow:
Sub poiuyt()
Dim K As Long, r As Range
Dim sh2 As Worksheet
Set sh2 = Sheets("Sheet2")
K = 1
With Sheets("Sheet1")
For Each r In .UsedRange
v = r.Value
If v <> "" Then
If Left(v, 1) = "W" Or Left(v, 2) = "IZ" Then
r.Copy sh2.Cells(K, 1)
K = K + 1
End If
End If
Next r
End With
End Sub

Select a hyperlink in one column based on "X" in adjacent column

So I'm fairly new to VBA, and I have been struggling with trying to get my macro to work.
Essentially what I'm trying to do is have a program read down a column, and for every "X" located in that column, the corresponding hyperlink in the adjacent column will be selected.
Sub Select_Hyperlinks()
Dim rng As Range, cell As Range, sel As Range
Dim sht As Worksheet
For x = 1 To 6
Set sht = Sheets("Generator")
Set sel = cell.Offset(-1, 0)
Set rng = Intersect(sht.Range("D4:D9"), sht.UsedRange)
For Each cell In rng.Cells
If (cell.Value) <> "X" _
Then
If sel Is Nothing Then
Set sel = cell.Offset(-1, 0)
sel.Select
End If
Next cell
End If
Next x
End Sub
I also tried a simpler idea using the Find and FindNext functions and for each X, I tried to get it to select and activate the cell in the adjacent column, but also with no luck. It seems I always get snagged up on the .Offset function.
EDIT:
Here's what I've managed to come up with, after some further research. I've adapted this from a macro designed to delete all empty rows.
Sub AutoOpen()
Dim xlastcell As Integer
Dim xcell As Integer
xcell = 1
Range("C200").End(xlUp).Select
xlastcell = ActiveCell.Cells 'This used to say ActiveCell.Row but I want a single cell'
Do Until xcell = xlastcell
If Cells(xcell, 1).Value = "X" Then
Cells(x, 1).Select
ActiveCell.Offset(0, -1).Select 'I'm also unable to get this function to work'
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
xcell = xcell - 1
xlastcell = xlastcell - 1
End If
xcell = xcell + 1
Loop
End Sub
Are you saying that if there is an X in the one column, you want to open the hyperlink?
EDIT:
Use this and change things to match your variables.
Sub asdhkl()
Dim c As Hyperlink
Dim i As Range
For Each i In Sheets(1).Range("b1:b3")
If i = "x" Then
Set c = i.Offset(0, -1).Hyperlinks(1)
c.Follow
End If
Next i
End Sub

Resources