Losing format excel cell using replace from VBA - excel

I'm using a excel template with labels that must be replaced with input values using VBA.
To do that I used the:
Cells.Replace What:="&/TDT/&", Replacement:="123456987654321456654444", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
True, ReplaceFormat:=False
But the displayed value in the cell after execute this replace is 1,23457E+23. I've tried to use different formats in the cell settings and I tried to change the ReplaceFormat and SeachFormat parameters without changes in the result.
Anyone has idea why excel doesn't respect the format of the cell?
The used format is Text for the replaced cell and the version of Office is 2007/2010. What I need is to see in the cell the 123456987654321456654444 instead of 1,23457E+23 after replacement.

What you can do is to combine using Value property and Find method to implement safe (or safer) replace like this:
Sub SafeReplace(ByVal What As String, ByVal Replacement As String)
Set cell = Cells.Find(What:=What, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False)
Do While Not cell Is Nothing
cell.Value = Replacement
Set cell = Cells.FindNext(cell)
Loop
End Sub
And then use it
SafeReplace "&/TDT/&", "123456987654321456654444"
It should respect the format of the cell.

' can be used in front of values to treat them as text:
Cells.Replace What:="&/TDT/&", Replacement:="'123456987654321456654444"

Related

How to replace default date (e.g. 0/1/1900) with blank using VBA?

Sub Macro9()
Range("Table57[Weld Done]").Select
Selection.Replace What:="0/1/1900", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=True, FormulaVersion:=xlReplaceFormula2
Range("Table57[[#Headers],[Weld Done]]").Select
End Sub
I used the Replace function to replace default date 0/1/1900 with "blank" & it worked. So I recorded the workflow using VBA macro recording function & it gives coding as above.
When I try to use the macro, the value remains as default date 0/1/1900.
Just change "0/1/1900" to 0 will do.
The issue is that the number 0 formatted as date is 0/1/1900
I assume that they are the result of a calculation (you use a formula in those cells).
You can change the .NumberFormat of your range to something like:
[=0]"";D/M/YYYY
and this will hide the zero dates and show the cells as blanks.

Excel - Stuck with VBA code to replace sheet names in date form in formulas

As the perhaps confusing title says, I'm writing a set of automated tools for a workbook and I've hit a roadblock.
I have a function that generates a new sheet and assigns it the current date as the name, in the format of "dd-mm-yyyy" (without quotation marks), and another that updates all required formulas in the new sheet.
There is a column that calculates the difference between the values in a column between the current and previous sheet. Upon running, the code executes and replaces the names but for some reason designates only the year as the sheet name, not the entire date. This results in an invalid reference error.
Example:
Previous sheet name: 23-5-2019
Current sheet name: 25-5-2019
The changed formula in the current sheet should be: =C3-'23-5-2019'!C3
But it instead becomes: =C3-23-5-'2019'!C3
The code for the replacement is below:
Sub FormulaUpdate()
range("D2:D100").Replace
What:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.count - 2).name,
Replacement:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.count - 1).name,
LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
Any help is much appreciated :)
I couldn't replicate this in code, it works as expected with the below when I name Sheet( 3) as 23-5-2019 and Sheet(2) as 25-5-2019
Sub Macro3()
to_replace = Sheets(3).Name
replace_val = Sheets(2).Name
Cells.Replace What:=to_replace, Replacement:=replace_val, LookAt:=xlPart _
, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
I'd suggest debugging step by step and confirming the values for the text to find and replacement values just before it takes place.
Also confirm that your new sheet has been created prior to doing the find / replace.
Hope that helps.

VBA replace everything in sheet except first rows

I have a working VBA script which currently replaces all dots by commas (posted below). However I would the script avoid the first two rows and change everything else. What would be the best and easiest way to do this? I have only found solutions where you have to set a range and but I want it to work for all excel sheets regardless of the number of rows or columns.
Sheets("Sheet1").Select
Cells.Replace what:=".", Replacement:=",", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
You can still use range, but generate it dynamically: use the macro recorder and see what it gives you if you select all cells with the Select All button at the top left corner, then hold down CTRL and unselect by clicking the row headers.
After having a selected range, you can use Application.Selection instead of Cells.
set wsCSV = ... (your csv worksheet)
set rng = wsCSV.UsedRange
set ws = ... (your worksheet)
ws.UsedRange.Offset(1).ClearContents()
ws.Range("A2").Resize(rng.Rows.Count, rng.Columns.Count).Values = rng.Values

Replace semi-colon with comma

I want to replace a semi-colon with a comma in a range.
The following code only deletes the semi-colon, it doesn't put the comma in its place.
Range("AU2:AU250").Select
Selection.Replace What:=";", Replacement:=",", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Try this ...
Sub Comma()
Dim R As Range, C As Range
Set R = Range([AU2], [AU250])
For Each C In R.Cells
C = Replace(C, ";", ",")
Next C
End Sub
This is IMHO a more VBA like approach making use of range objects rather than simulating Excel stuff that you would use when interacting directly with your sheet
Can you copy paste some of the offending cells from the CSV range in the csv file? Open it in wordpad though, not in excel.
Also, what version of excel are you using? I haven't managed to get this to occur either on 2003 or 2010.
And I assume you need to do this more than once is why you are making a macro or is find/replace failing and you are posting macro code to get help with that too? :-)

Get reference to next visible cell in autofiltered table

I have a UserForm that sits on top of my spreadsheet and simply displays information from the row containing the currently selected cell. Buttons on the form allow the user to move up/down the spreadsheet row by row. For example, when the "next record" button is clicked, the code executed is something like:
Cells(ActiveCell.Row + 1, ActiveCell.Column).Select
LoadValues
I would like it to work even if the user filters the data and then loads the form. However, using the above code, it wants to loop through all cells, not just the ones still visible after filtering. I've seen solutions for immediately looping through only visible cells, e.g.,
For Each viscell In rng.SpecialCells(xlCellTypeVisible)
...
Next viscell
So there seems like there should be a better, more direct way to do this than looping through all rows until I get to the next one with .Hidden = False but I can't seem to figure out how to get a reference to "the next visible cell" in order to select it.
Any pointers would be greatly appreciated. Thanks.
Here's a lightning-quick way to activate the first not-blank, visible cell in a filtered range. Just change 'Range("A1")' to whatever range you'd like to search after. Also consider whether you want xlByColumns or xlByRows.
ActiveSheet.Cells.SpecialCells(xlCellTypeVisible).Find(What:="*", _
After:=ActiveSheet.Range("A1"), LookIn:=xlFormulas, lookat:=xlPart, searchorder:=xlByColumns, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
I recommend using tables whenever possible, as they have variable named ranges built-in that are easy to reference.
Here's another example, using tables. It's targeted to search a specific column, so it'll be even faster.
Just find and replace TABLE_NAME and COLUMN_NAME with your values.
ActiveSheet.Range("TABLE_NAME[[#All], COLUMN_NAME]]").SpecialCells(xlCellTypeVisible).Find _
(What:="*", After:=ActiveSheet.Range("TABLE_NAME[[#Headers],[COLUMN_NAME]]"), _
LookIn:=xlFormulas, lookat:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
No loops required because it's built off of Excel's "Find" functionality.
And just a tip,you can also use this to grab the data of such a cell on separate worksheet without activating/selecting it at all.
Just find and replace Dbl_EXAMPLE, SHEET_NAME, TABLE_NAME and COLUMN_NAME with your references.
Dim Dbl_EXAMPLE as Double
Dbl_EXAMPLE = Sheets("SHEET_NAME").Range("TABLE_NAME[[#All], COLUMN_NAME]]").SpecialCells(xlCellTypeVisible).Find _
(What:="*", After:=Sheets("SHEET_NAME").Range("TABLE_NAME[[#Headers],[COLUMN_NAME]]"), _
LookIn:=xlFormulas, lookat:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Value2
Just replace ".Value2" at the end with whatever property you're looking for.
Examples:
.Formula
.Row
.Column
The list goes on
I really struggled with this too and used Ryan's solution, albeit a little abbreviated, for my purposes..
This may be as brief as it gets. :)
ActiveCell.EntireColumn.SpecialCells(xlCellTypeVisible).Find(What:="*", After:=ActiveCell).Activate
Here is one method using a simple loop until the next row down is visible.
Dim rng As Range
Set rng = ActiveCell
Dim n As Long: n = 1
Do Until rng.Offset(n, 1).Rows.Hidden = False
n = n + 1
Loop
rng.Offset(n, 1).Select
LoadValues

Resources