Matthew Tapp
New Member
- Joined
- Nov 30, 2020
- Messages
- 4
- Office Version
- 365
- Platform
- MacOS
I have built a VBA macro to do a find and replace process on a specified range, referencing ranges for the "what" and "replacement" terms. The find and replace works but it is removing leading zeros from the replacement terms.
Here is a simplified sample of the code....
Range("A1").Replace What:=Range("B1"), Replacement:=Range("C1"), LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=True,
Cell C1 refers to a 3-digit code that begins with a zero (ex. 020). (Please note: this is a simple version of the code I've been using to trial and error this issue. The full code references a table and loops through a series of numbers, some beginning with zero and some not.). The number format of C1 is set to text. I've also added an apostrophe beforehand (i.e. '020).
When I run this macro, it removes the leading zero and writes "20" in A1. I've tried numerous things to correct this, with no success, including defining the ReplaceFormat in the code, defining the number format of A1, and using the substitute method instead of replace.
The code works if I the replacement value is spelled out in the code (i.e. "'020") rather than referencing a range. It only fails to work when referencing a range. I don't want to explicitly write out the replacement terms because there's dozens and the list can grow, so I want users who don't know VBA to be able to add to the list as needed).
Additionally, I noticed a peculiar quirk... if the target range (A1) previously contained the value 020, then it will write it correctly, even after formatting is deleted.
Here is a simplified sample of the code....
Range("A1").Replace What:=Range("B1"), Replacement:=Range("C1"), LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=True,
Cell C1 refers to a 3-digit code that begins with a zero (ex. 020). (Please note: this is a simple version of the code I've been using to trial and error this issue. The full code references a table and loops through a series of numbers, some beginning with zero and some not.). The number format of C1 is set to text. I've also added an apostrophe beforehand (i.e. '020).
When I run this macro, it removes the leading zero and writes "20" in A1. I've tried numerous things to correct this, with no success, including defining the ReplaceFormat in the code, defining the number format of A1, and using the substitute method instead of replace.
The code works if I the replacement value is spelled out in the code (i.e. "'020") rather than referencing a range. It only fails to work when referencing a range. I don't want to explicitly write out the replacement terms because there's dozens and the list can grow, so I want users who don't know VBA to be able to add to the list as needed).
Additionally, I noticed a peculiar quirk... if the target range (A1) previously contained the value 020, then it will write it correctly, even after formatting is deleted.