VBA to put apostrophe if cell not empty

craigg3

Board Regular
Joined
Dec 23, 2002
Messages
161
Office Version
  1. 2013
Platform
  1. Windows
I have a range of cells (E7:J50) that I need to put a leading apostrophy to any of the cells that are not empty. After my macro runs, I also need to remove the leading apostrophy from non empty cells (E7:J50)
 

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
Hi

This will put an apostrophy to all cells that're not empty;
VBA Code:
Dim c As Range

For Each c In Range("E71:J50")
If c.Value <> "" Then
c.Value = "'" & c.Value
End If
Next

Just so I'm clear on the second point, the above code won't input data into any blank cells. Do you still need to remove the apostrophy for these other cells? If so, does the cell only have an apostrophy in it or is there some other contents too?
 
Upvote 0
Can you explain why you need the apostrophe before the macro runs and not after it runs? Can you please post the macro you are using?
 
Upvote 0
Hi

This will put an apostrophy to all cells that're not empty;
VBA Code:
Dim c As Range

For Each c In Range("E71:J50")
If c.Value <> "" Then
c.Value = "'" & c.Value
End If
Next

Just so I'm clear on the second point, the above code won't input data into any blank cells. Do you still need to remove the apostrophy for these other cells? If so, does the cell only have an apostrophy in it or is there some other contents too?

It would just need to remove the leading apostrophy from any non-empty cells. The non-blank cells will have more than just an apostrophy in it.
 
Upvote 0
How about
VBA Code:
Sub craigg()
   With Range("E7:J50")
      .Value = Evaluate(Replace("if(@="""","""",""'""&@)", "@", .Address))
   End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,883
Messages
6,122,077
Members
449,064
Latest member
MattDRT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top