Home » excel » How To Remove Excel VBA's $ sign from code

How To Remove Excel VBA's $ sign from code

Posted by: admin March 9, 2020 Leave a comment

Questions:

I have the below code:

Sub poorguy()
Dim counter As Long
Dim countto As Long
Dim col1 As String
Dim col2 As String
Dim col3 As String
Dim col4 As String
Dim rngwrite As Range

counter = 0
countto = 100

For i = 0 To countto
    col1 = Cells(12, 2).Offset(0, counter).Address
    col2 = Cells(12, 3).Offset(0, counter).Address
    col3 = Cells(3, 2).Offset(0, counter).Address
    col4 = Cells(3, 3).Offset(0, counter).Address
    Set rngwrite = Cells(58, 3).Offset(counter, counter)
    rngwrite.Value = "=(" & col1 & "-" & col2 & ")*" & col3 & "*" & col4
    counter = counter + 1
Next
Set rngwrite = Nothing
End Sub

The problem is that it generates too many $ in the formula. For example,
it gives: =($B$12-$C$12)*$B$3*$C$3

What I want is: =($B$12-C12)*$B$3*C3

How do I remove the extra $’s?

How to&Answers:

Add (false, false) to the address you do not want absolute values for.

Sub poorguy()
Dim counter As Long
Dim countto As Long
Dim col1 As String
Dim col2 As String
Dim col3 As String
Dim col4 As String
Dim rngwrite As Range

counter = 0
countto = 100

For i = 0 To countto
    col1 = Cells(12, 2).Offset(0, counter).Address
    col2 = Cells(12, 3).Offset(0, counter).Address(false, false)
    col3 = Cells(3, 2).Offset(0, counter).Address
    col4 = Cells(3, 3).Offset(0, counter).Address(false, false)
    Set rngwrite = Cells(58, 3).Offset(counter, counter)
    rngwrite.Value = "=(" & col1 & "-" & col2 & ")*" & col3 & "*" & col4
    counter = counter + 1
Next
Set rngwrite = Nothing
End Sub

Answer:

One way is to get rid of all $ characters in your string with Replace, after it’s been set with the address but before it’s used to create the formula:

col2 = Replace(col2, "$", "")

(and ditto for col4).

Alternatively, the first two arguments to Address dictate whether the row and column portion are generated as relative (false) or absolute (true, the default). That gives more more fine-grained control over the generated string.