This skinnied down version worked ok for me when I ran it:
Option Explicit
Sub testme()
Dim myFileName As String
Dim wkbk As Workbook
myFileName = "C:\my documents\excel\book1.xls"
Set wkbk = Workbooks.Open(Filename:=myFileName, ReadOnly:=True)
ThisWorkbook.VBProject.References.AddFromFile Filename:=myFileName
End Sub
Book1.xls had a project name of Book1 (changed from VBAProject).
Book1.xls was not marked readonly (in windows), but opened readonly.
And I had Tools|Macro|security|Trusted Publishers tab
Trust access to Visual Basic Project checked
If you can't get it working, you may want to share more information--what is the
error you receive when you run the code.
(E-Mail Removed) wrote:
>
> Unfortunately Dave's solution doesn't do quite what I am wanting ...
> perhaps i didnt explain myself properly
>
> Just to clarify what i wish to do is:
> a) have wrkbk1 open
> b) from wrkbk1 VBA code create a reference to another workbook
> 'wrkbk2' which must be opened as a Read Only item.
> I want to create a refence .. which you could manually
> create by
> Tools > References > Browse (from the VB editor)
>
> The way I was going about it was first, open a read only version of
> wrkbk2 (as Dave's code does) and then try to create the reference.
>
> A further note: my original code seems to work when i debug it ... it
> throws an error but then works. But when it comes to run-time it just
> throws the error.
>
> On Apr 19, 2:48 pm, "NickHK" <TungChe...@Invalid.com> wrote:
> > Doesn't Dave's solution work ? You set the reference when you open it
> > read-only, not before or after.
> >
> > set wkbk = workbooks.open(filename:=myfilename,readonly:=true)
> >
> > NickHK
> >
> > <a.years...@gmail.com> wrote in message
> >
> > news:(E-Mail Removed)...
> >
> >
> >
> > > Yea I open the workbook as a Read Only document, then try to set the
> > > reference to it. But because it is already open it throws the error.
> >
> > > If I set the reference to it while it is still closed then it
> > > automatically opens it in read/write format ... but i need it to be in
> > > read only.- Hide quoted text -
> >
> > - Show quoted text -
--
Dave Peterson