What to do when your String variable contains an apostrophe

jardenp

Active Member
Joined
May 12, 2009
Messages
373
Office Version
  1. 2019
  2. 2016
  3. 2013
  4. 2011
  5. 2010
Platform
  1. Windows
I am trying to assign a workbook name to a String variable
Code:
Dim WeeklyRoutesWorkbook As String
    WeeklyRoutesWorkbook = ActiveWorkbook.Name
When I try to call this later, I get an error
Code:
 Range("G2").FormulaR1C1 = _
        "=VLOOKUP(RC[-1],'[" & WeeklyRoutesWorkbook & "]Sheet1'!C5:C9,5,FALSE)"
My testing shows this is because the WeeklyRoutesWorkbook contains an apostrophe (i.e., the original ActiveWorkbook name contains an apostrophe).

Is there a way around this? This script will be run on many workbooks, which all contain an apostrophe in their names.

I looked at this but couldn't make sense of it: https://msdn.microsoft.com/en-us/library/office/aa212167(v=office.11).aspx

Thanks!

JP in IN
 

Excel Facts

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
Caveat - This isn't helpful at all..

Why are your users creating files with an apostrophe in the file name?!
 
Upvote 0
You need to double the apostrophe as you would entering the formula manually:
Code:
 Range("G2").FormulaR1C1 = _
        "=VLOOKUP(RC[-1],'[" & Replace$(WeeklyRoutesWorkbook, "'", "''") & "]Sheet1'!C5:C9,5,FALSE)"
 
Upvote 0
Because they're clearly not as tech savvy as you, Slinky.

I've stopped the practice, but that doesn't change the old files.
 
Upvote 0
Thank you, RoryA. It's much appreciated!
 
Upvote 0
I just tested this and it works. Thanks again, RoryA
 
Upvote 0

Forum statistics

Threads
1,223,098
Messages
6,170,100
Members
452,301
Latest member
QualityAssurance

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