View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
PBcorn PBcorn is offline
external usenet poster
 
Posts: 79
Default referencing a workbook using string var = error9

I'm getting a subs out of range error for the following (section taken from
sub)-

For j = 1 To 4

c = "dataname" & Format(j)
If j = 1 Or j = 2 Then u = v Else u = "TOTAL DATA"
MsgBox c 'first iter gives dataname1 as i would expect
MsgBox u 'first iter gives worksheet name in v as i would expect
MsgBox Workbooks(c).Worksheets(u).Name 'generates error 9
Exit Sub
With Workbooks(c).Worksheets(u) 'generates error 9
.Cells(1, 1).Value = "p"
.Cells(1, 2).Value = "q
.Cells(1, 3).Value = "r"
.Cells(1, 4).Value = "s"
.Cells(1, 5).Value = "t"
.Cells(1, 6).Value = "u"
.Cells(1, 7).Value = "v"
.Cells(1, 8).Value = "w"
.Cells(1, 9).Value = "x"
.Range("a1:i1").Interior.Color = vbRed
End With

Next j

notes:

dataname1 through 4 is dim as string
workbooks called dataname 1 through 4 are all open
v is a string assigned previusly which is the name of the worksheet just
added to the workbooks

c,u, dim as string


msgbox stataments used to debug - c and u variables contain what i would
expect

WHY is this not working!!

Thanks

PB