Substitute Function in Excel VBA for cell range - vba

I have to replace one character with another in Excel file.
I have used following Replace function, but due to exceeds of 1024 character limit in some cells, it stops there.
Sub Replace()
With Sheets("Sheet1").Range("A1:A629")
.Cells.Replace ",", ";", xlPart, xlByRows, False
End With
End Sub
I got to know Substitute function would do
Cells(1, 2) = "=SUBSTITUTE(A1,"","","";"")"
But how do I use that for cell range?

Try this
Sub Replace()
Dim rng As Range, cell As Range
Set rng = Sheets("Sheet1").Range("A1:A629")
For Each cell In rng
cell = WorksheetFunction.Substitute(cell, ",", ";")
Next
End Sub

Try this. Note that it uses the VBA Replace function, so you need to rename your 'Replace` subroutine.
Sub ReplaceText()
For Each c In Sheets("Sheet1").Range("A1:A629").Cells
c = Replace(c.Value, ",", ";")
Next c
End Sub
Note: This will only work if you have values in the cells, no Formulas. Because Excel has a formula length limit of 1024 characters. But given you have this specific error, your cells must not be formulas.

Related

VBA: Convert all worksheet text to number

I'm looking to to convert automatically all number stored as text in worksheet to numbers with VBA. Excel seems to detect automatically theses values, there is a way in VBA to convert all theses numbers ?
I found this following solution to convert a text to a number, but i want this apply to all the worksheet and not to a specify Range, because the worksheet is dynamic.
Range("F:F").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
Somebody have an idea ?
with activesheet.usedRange
.numberFormat = "General"
.value = .value
End with
Guessing that the problem is in the different decimal separator, which is quite a big problem in Germany and France. If this is the case, this works:
Option Explicit
Public Sub TestMe()
On Error GoTo TestMe_Error
Dim myCell As Range
Dim tryCell As String
For Each myCell In Cells.SpecialCells(xlCellTypeConstants)
tryCell = Replace(myCell, ",", ".")
If IsNumeric(tryCell) Then
myCell = Replace(myCell, ",", ".")
End If
Next myCell
On Error GoTo 0
Exit Sub
TestMe_Error:
MsgBox "No contant values!"
End Sub
The code checks all the cells without formula in the ActiveSheet. Then, if by changing the , to a . the cell would become numeric, it changes it.

Another >> Unable to set the FormulaArray property of the range class

I've researched as many of the "Unable to set the FormulaArray property of the range class" issues here and in other sites to troubleshoot a FormulaArray operation I'm trying to carry out in a table of data.
I've respected the 255 character limit in my formula taking into account R1C1, I've tried to insert the formula as a text string first. I've tried quite a few things.
Now I'm thinking my issue is with the fact that I'm trying to insert my formula only into blank cells because if I simplify my formula to only be =1+1 I still get the error. If I change .FormulaArray to .Formula to simply enter a standard formula I also get the same error. Is this operation not possible with blank cells?
The error occurs at the .FormulaArray = myFormula1 step.
To confirm, the formula by itself works (pasted further below) when entered into cells manually.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(INDEX(MLB," & "X_X_X)"
myFormula2 = "transactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),," & "Y_Y_Y)"
myFormula3 = "5)=$A2,""DNP/SUS/MIN"",""with "" & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions," & "Z_Z_Z)"
myFormula4 = "!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK""))"
Sheets("Sheet1").Select
With Range("E2:AZ140").SpecialCells(4)
.FormulaArray = myFormula1
.Replace ",X_X_X)", myFormula2
.Replace ",Y_Y_Y)", myFormula3
.Replace ",Z_Z_Z)", myFormula4
End With
End Sub
Question update. Using With Range("E2:AZ140").SpecialCells(xlCellTypeBlanks) instead of With Range("E2:AZ140").SpecialCells(4) also ends with the same error.
Here is the full formula being used
=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,"<="&$C2)>0,IF(INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)=$A2,"DNP/SUS/MIN","with " & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,"DNP/SUS/MIN","LEAVE BLANK"))
Testing with a simplified code (example below) led to the realization as YowE3K points out that myFormula1 needs to be valid in order for the procedure to work.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
myFormula1 = "=1+1" & "+2+2"
myFormula2 = "+1+1"
Sheets("Sheet1").Select
With Range("h14:h16").SpecialCells(xlCellTypeBlanks)
MsgBox .Address
.FormulaArray = myFormula1
.Replace "+2+2)", myFormula2
End With
End Sub
When you set a formula using FormulaArray = ..., it needs to be a valid formula. (I think after each Replace the formula needs to continue being valid too, but I haven't tested that. Edit: No, if the Replace would create an invalid formula, it just doesn't process it - but it doesn't crash.)
Your problems all seem to stem from the use of invalid formulas in your myFormula1 variable.
I suggest you use the following:
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(1232=$A2,""DNP/SUS/MIN"",""with ""&1233),1234)"
myFormula2 = "INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)"
myFormula3 = "INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)"
myFormula4 = "IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK"")"
'Insert the formula
With Sheets("Sheet1").Range("E2:AZ140").SpecialCells(xlCellTypeBlanks)
.FormulaArray = myFormula1
.Replace "1232", myFormula2
.Replace "1233", myFormula3
.Replace "1234", myFormula4
End With
End Sub
Setting .FormulaArray to a range of cells in VBA is the same as pressing CTRL+SHIFT+ENTER while the entire range is selected. This is used when a single formula is returning an array of results and you want to display that array in the range of selected cells. This requires a contiguous range of cells to display the array. Trying to set .FormulaArray on a non-contiguous range of cells will fail, regardless of whether the formula is good or not.
I think you're trying to create an Array Formula that returns a single result after performing analysis on arrays; and you want this formula used in all blank cells.
In Excel, you would need to array-enter the formula into a single cell and then copy the formula into other cells.
Similarly, you need to do it in 2 steps in VBA. You need to first set the .FormulaArray for just one cell. This will also confirm that the formula is being constructed correctly in VBA. You can then copy that cell to all blank cells, using PasteSpecial if you only want to copy the formula.
Alternatively, you could loop through all blank cells setting the .FormulaArray individually, e.g.:
Dim raCell As Range
For Each raCell In Range("E2:AZ140")
If IsEmpty(raCell) Then raCell.FormulaArray = ...
Next
However, as you have dynamic references, you would need to construct the FormulaArray carefully to correctly determine the formula required based on the .Row and .Column of the current raCell.
Copy and paste would be safer if you have an "achor" point. Somewhere you know you can always enter the exact same formula and get the correct result when copied and pasted to all other cells.

Excel vba Autofill only empty cells

I have a column A with data up to A300.
In this range, some of theses cells are empty, some contain values.
In VBA, I set the formula of the cell A1 then I use the autofill function to set it all over my column (up to A300) like this :
ws.Range("A1").Select
Selection.AutoFill Destination:=ws.Range(ws.Cells(1, 1), ws.Cells(300, 1))
My problem is that datas contain on some cells are erased too ! I'm trying to autofill like it but only throught the empties cells.
I tried to add a filter on my worksheet like this :
ws.Range("$A$1:$A$300").AutoFilter Field:=1, Criteria1:="="
Then I reused the autofill function, but it seems to fill thourght the filtered cells...
Can't we add a parameter like "only empties cells" to the autofill function ? Something like this :
Selection.AutoFill Destination:=ws.Range(ws.Cells(1, 1), ws.Cells(300, 1)), Criteria1:="="
Thanks for your replies !
with data like:
I would do a single copy rather than a fill-down:
Sub luxation()
Range("A1").Formula = "=ROW()"
Dim rDest As Range
Set rDest = Intersect(ActiveSheet.UsedRange, Range("A1:A300").Cells.SpecialCells(xlCellTypeBlanks))
Range("A1").Copy rDest
End Sub
with this result:
NOTE:
The formulas adjust after being copied.
EDIT#1:
Please note that there are some circumstances under which this code will not work. It is possible that UsedRange my not extend down to cell A300.
For example, if the worksheet is totally empty except for a formula in A1 and some value in A3. In this case Rdest will only include the single cell A2. The code will leave A4 through A300 untouched.
Assuming you want static values, I would use a loop. The one below will fill all empty cells with poop:
Sub AllFillerNoKiller()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
For Each c In ws.Range("A1:A300")
If c.Value = "" Then c.Value = "poop"
Next
End Sub
Apologies, I miss-understood you question - Want to fill all blank cells with the value in A1? - here you go:
Sub Replace()
If Trim(Range("A1").Value) = "" Then
MsgBox "There's no value in A1 to copy so there's nothing to copy to all blank cells", vbInformation, "Nothing in A1"
Exit Sub
Else
Range("A1:A300").SpecialCells(xlCellTypeBlanks).Select
Selection.Value = Range("A1").Value
End If
End Sub
You can also use below code:
stAddress = Sheet1.Range("A1").CurrentRegion.SpecialCells(xlCellTypeBlanks).Address
Sheet1.Range(st).Value = "Empty"

VBA search and copy

I'm automating an update I have to do and part of the macro I want to write needs specific text from what gets populated.
I have the following types of text in the same column for hundreds of rows:
ScreenRecording^naushi02^procr^10035
procr^10635^ScreenRecording^misby01
ScreenRecording^liw03^procr^10046
I've bold the text I need. I want to either replace the whole text with just what I need or place what I need in the next column, same row.
I had wrote something which worked for 60 or so lines before I realised that there are variations in the format. For the main, it's all the same which is why I didn't realise at first and I've spent a lot of wasted time writing something that is now useless... so I'm asking for expert help please.
Once I've got what I need from the first row, I need to move down until the last entry repeating.
I had some code which obviously didn't work fully.
I have thought about using the text 'ScreenRecording' in a search along with the special character which I can't find on my keyboard and then trying to copy all text from that point upto and including the 2nd numerical character. I don't know how to do this, if it would work or even if it's a good idea but because I've spent so much time trying to figure it out, I need some help please.
Thanks in advance
If you always want to return the value after the word 'ScreenRecording`, you can use the following function to do so.
Include it in a SubRoutine to replace in place if needed:
Function SplitScreenRecording(sInput As String) As String
Dim a As Variant
Const SDELIM As String = "^"
Const LOOKUP_VAL As String = "ScreenRecording"
a = Split(sInput, SDELIM)
If IsError(Application.Match(LOOKUP_VAL, a, 0)) Then
SplitScreenRecording = CVErr(2042)
Else
SplitScreenRecording = a(Application.Match(LOOKUP_VAL, a, 0))
End If
End Function
Sub ReplaceInPlace()
Dim rReplace As Range
Dim rng As Range
Set rReplace = Range("A1:A3")
For Each rng In rReplace
rng.Value = SplitScreenRecording(rng.Value)
Next rng
End Sub
if you want to replace:
Sub main2()
Dim key As String
Dim replacementStrng As String
key = "ScreenRecording"
replacementStrng = "AAA"
With Worksheets("mysheet01").columns("A") '<--| change "mysheet01" and "A" to your actual sheet name and column to filter
.Replace what:=key & "^*^", replacement:=key & "^" & replacementStrng & " ^ ", LookAt:=xlPart
.Replace what:="^" & key & "^*", replacement:="^" & key & "^" & replacementStrng, LookAt:=xlPart
End With
End Sub
while if you want to place what you need in the next column:
Sub main()
Dim myRng As Range
Set myRng = GetRange(Worksheets("mysheet01").columns("A"), "ScreenRecording^") '<--| change "mysheet01" and "A" to your actual sheet name and column to filter
myRng.Offset(, 1) = "value that I need to place in next row" '<--| change the right part of the assignment to what you need
End Sub
Function GetRange(rng As Range, key As String) As Range
With rng
.AutoFilter Field:=1, Criteria1:="*" & key & "*" '<--| apply current filtering
If Application.WorksheetFunction.Subtotal(103, .Cells) > 0 Then '<--| if there are visible cells other than the "header" one
With .SpecialCells(xlCellTypeConstants)
If InStr(.SpecialCells(xlCellTypeVisible).Cells(1, 1), key & "^") > 0 Then
Set GetRange = .SpecialCells(xlCellTypeVisible) '<--|select all visible cells
Else
Set GetRange = .Resize(.Parent.Cells(.Parent.Rows.Count, .Column).End(xlUp).row - 1).Offset(1).SpecialCells(xlCellTypeVisible) '<--|select visible rows other than the first ("headers") one
End If
End With
End If
.Parent.AutoFilterMode = False '<--| remove drop-down arrows
End With
End Function

Use User-defined range as input for cell parsing

I'm writing a macro in Excel 2010 in order to remove line breaks in multiple cells of a column. This cells need to be selected by the user. Following this previous post I was able to create an InputBox to let the user select the range but now, I am unable to process the data within the selection.
My previous code without the selection range parsed an entire column with a regexp to find a pattern in the string within the cells and change its contents.
I did this with a For i To Rows.Count block of code like this:
For i = 1 To Rows.Count
If Not IsEmpty(Cells(i, 5).Value) Then
varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text
Sheets(ActiveSheet.Name).Cells(i,5).Value=objRegExp.Replace(varString, "$1 ")
End If
Next i
Now I want to replace the static column so I can process only the user range.
In order to achieve that I tried this:
Set selection = Application.InputBox(Prompt:= _
"Please select a range to apply the remove break lines procedure.", _
Title:="Remove Line Breaks", Type:=8)
If selection Is Nothing Then
Exit Sub
End If
Set RowsNumber = selection.CurrentRegion -> This line gives me an error: "Object required"
Set RowsNumber = RowsNumber.Rows.Count
For i = 1 To RowsNumber
If Not IsEmpty(Cells(i, 5).Value) Then
varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text
Sheets(ActiveSheet.Name).Cells(i, 5).Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
End If
Next i
How can I access the cells in the range returned by the InputBox?
I also tried changing RowsNumber with selection.Rows.Count but that way, although it doesn't gives an error, the cells used have blank string within them when I run the debugger. I think this is because I try to access row = 5 when the range could be less, i.e 3 if user just selects 3 cells.
I tried a For Each Next loop but then again, I know not how to access the cells withing the selection range.
You can iterate through the cells of a range by using For Each loop.
Below is your code modified. I have changed the name of variable Selection to rng, because Selection is Excel library built-in function and this name should be avoided.
Sub x()
Dim rng As Excel.Range
Dim cell As Excel.Range
Set rng = Application.InputBox(Prompt:= _
"Please select a range to apply the remove break lines procedure.", _
Title:="Remove Line Breaks", Type:=8)
If rng Is Nothing Then
Exit Sub
End If
For Each cell In rng.Cells
If Not IsEmpty(cell.Value) Then
varString = cell.Text
cell.Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
End If
Next cell
End Sub