Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I am trying to write a macro in Excel VBA with the following properties: replace 123 with hello original after replacement 12345678 hello45678 (123 is

I am trying to write a macro in Excel VBA with the following properties:

replace "123" with "hello"

original after replacement
12345678 hello45678 (123 is on the left)
123986604860 hello986604860 (123 is on the left)
037073058 037073058 (no 123)
99912398598 99912398598 (no replacement since 123 is in the middle)
123 123 (no replacement since it's alone)

My problem is the results always come up as 0 no matter what I type and I don't know what is wrong with that. The formula works when I type the formula in a particular cell but does not work in VBA. Could you please help to debug?

These are my codes:

Sub fastReplace() ' ' fastReplace Macro ' ' Keyboard Shortcut: Ctrl+d 'PURPOSE: Apply the Formula To A Cell Range

Dim rng As Range Dim DefaultRange As Range Dim FormatRuleInput As String Dim oldStr As String Dim newStr As String Dim length As Integer

'Determine a default range based on user's Selection If TypeName(Selection) = "Range" Then Set DefaultRange = Selection Else Set DefaultRange = ActiveCell End If

'Get the old text to be replaced oldStr = Application.InputBox( _ Title:="Fast Replace - Old Text", _ Prompt:="Please enter the old text to be replaced.")

'Get the new text newStr = Application.InputBox( _ Title:="Fast Replace - New Text", _ Prompt:="Please enter your new text.")

'Get A Cell Address From The User to Get Number Format From Set rng = Application.InputBox( _ Title:="Fast Replace", _ Prompt:="Select a cell range to apply fast replace", _ Default:=DefaultRange.Address, _ Type:=8)

'Test to ensure User Did not cancel If rng Is Nothing Then Exit Sub length = CInt(Len(oldStr)) 'Apply formula to Cell Range rng.Formula = "=IF(AND(LEFT(RC,length)=oldStr,CInt(Len(RC))>length),REPLACE(RC,1,length,newStr),RC)"

End Sub

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Structured Search For Big Data From Keywords To Key-objects

Authors: Mikhail Gilula

1st Edition

012804652X, 9780128046524

More Books

Students also viewed these Databases questions

Question

If ( A^2 - A + I = 0 ), then inverse of matrix ( A ) is?

Answered: 1 week ago

Question

What is computer neworking ?

Answered: 1 week ago