473,503 Members | 2,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How does nesting of With ... End With affect scope of variables?

I got bored today, so I decided to rewrite the code in KB article 316383 to
decrease the number of object references.
This resulted in a number of nested With ... End With.

The original code had a

Dim r As Integer, c As Integer

shortly before a For Next.

The original code does not use With ... End With.

I ended up with, no pun intended, the code below. If the Dim statement is
moved into more deeply nested With ... End Withs, there are compile errors.

I've included the statement twice below. I've commented out the case that
does work, so you should see a compile error.

Ordinarily such statements should be at the beginning of the procedure.
Are there any restrictions for placing PROCEDURE level Dim declaration
statement?
Where are these documented?

Imports Microsoft.Office.Interop
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim oWord As Word.Application
Dim Pos As Double
Dim r As Integer, c As Integer
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
With oWord
..Visible = True
Pos = .InchesToPoints(7)
..Documents.Add()
With .ActiveDocument
'Dim r As Integer, c As Integer ' This works
'Insert a paragraph at the beginning of the document.
With .Content
Dim r As Integer, c As Integer ' This fails
..InsertAfter(Text:="Heading 1")
..Font.Bold = True
..Paragraphs(1).SpaceAfter = 24 '24 pt spacing after paragraph.
..InsertParagraphAfter()
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
'Insert a paragraph at the end of the document.
..InsertAfter(Text:="Heading 2")
..Paragraphs(1).SpaceAfter = 6
..InsertParagraphAfter()
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
..InsertAfter(Text:="This is a sentence of normal text. Now here is a
table:")
'Insert another paragraph.
..InsertParagraphAfter()
..Paragraphs(.Paragraphs.Count).Range.Font.Bold = False
..InsertParagraphAfter()
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
'Insert a 3 x 5 table, fill it with data, and make the first row
'bold and italic.
With .Tables.Add(.Bookmarks.Item("\endofdoc").Range, 3, 5)
With .Range
..ParagraphFormat.SpaceAfter = 6
..Font.Bold = False
End With
For r = 1 To 3
For c = 1 To 5
..Cell(r, c).Range.Text = "r" & r & "c" & c
Next
Next
With .Rows.Item(1).Range.Font
..Bold = True
..Italic = True
End With
End With
End With
With .Content
'Add some text after the table.
..Paragraphs(.Paragraphs.Count).Format.SpaceAfter = 24
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
..InsertParagraphAfter()
End With
With .Paragraphs(.Paragraphs.Count)
..SpaceAfter = 24
With .Range
..Text = "And here's another table:"
..Font.Bold = False
..InsertParagraphAfter()
End With
End With
'Insert a 5 x 2 table, fill it with data, and change the column widths.
With .Tables.Add(.Bookmarks.Item("\endofdoc").Range, 5, 2)
..Range.ParagraphFormat.SpaceAfter = 6
For r = 1 To 5
For c = 1 To 2
..Cell(r, c).Range.Text = "r" & r & "c" & c
Next
Next
With .Columns
..Item(1).Width = oWord.InchesToPoints(2) 'Change width of columns 1 & 2
..Item(2).Width = oWord.InchesToPoints(3)
End With
End With
'Keep inserting text. When you get to 7 inches from top of the
'document, insert a hard page break.
With .Content
..InsertParagraphAfter()
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
Do
..ParagraphFormat.SpaceAfter = 6
..InsertAfter("A line of text")
..InsertParagraphAfter()
..Collapse(direction:=Word.WdCollapseDirection.wdC ollapseEnd)
Loop While Pos >=
..Information(Word.WdInformation.wdVerticalPositio nRelativeToPage)
..InsertBreak(Word.WdBreakType.wdPageBreak)
..Collapse(Word.WdCollapseDirection.wdCollapseEnd)
..InsertAfter("We're now on page 2. Here's my chart:")
..InsertParagraphAfter()
End With
'Insert a chart and change the chart.
With .Bookmarks.Item("\endofdoc").Range.InlineShapes.Ad dOLEObject( _
ClassType:="MSGraph.Chart.8", FileName _
:="", LinkToFile:=False, DisplayAsIcon:=False)
With .OLEFormat.Object
..charttype = 4 'xlLine = 4
With .Application
..Update()
..Quit()
End With
End With
'If desired, you can proceed from here using the Microsoft Graph
'Object model to make additional changes to the
'chart.
..Width = oWord.InchesToPoints(6.25)
..Height = oWord.InchesToPoints(3.57)
End With
'Add text after the chart.
With .Content
..InsertParagraphAfter()
..InsertAfter("THE END.")
End With
End With
End With
oWord = Nothing
'All done. Close this form.
Me.Close()
End Sub
End Class

--
http://www.standards.com/; See Howard Kaikow's web site.
Nov 21 '05 #1
8 2007
* "Howard Kaikow" <ka****@standards.com> scripsit:
Dim r As Integer, c As Integer
This can be shortened to 'Dim r, c As Integer'.
The original code does not use With ... End With.

I ended up with, no pun intended, the code below. If the Dim statement is
moved into more deeply nested With ... End Withs, there are compile errors.

I've included the statement twice below. I've commented out the case that
does work, so you should see a compile error.

Ordinarily such statements should be at the beginning of the procedure.
Are there any restrictions for placing PROCEDURE level Dim declaration
statement?
Where are these documented?
Visual Basic Language Specification -- 10.2 Local Declaration Statements
<URL:http://msdn.microsoft.com/library/en-us/vbls7/html/vblrfvbspec8_3.asp>

"
Local variables, local constants, and static variables are scoped to the
statement block in which they are declared.
"

Visual Basic Language Reference -- 'Dim' Statement
<URL:http://msdn.microsoft.com/library/en-us/vblr7/html/vastmdim.asp>

"
Variables declared inside a procedure or a block are accessible only
from within that procedure or block.
"

Notice that the variable is not visible in front of the line it's dimmed
on:

\\\
i = 10
Dim i As Integer
///

.... will fail to compile.
Imports Microsoft.Office.Interop
Public Class Form1
[A log of code without indentation]


Do you have an indented version of the source code too :-)?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 21 '05 #2
On 2004-09-12, Howard Kaikow <ka****@standards.com> wrote:
I got bored today, so I decided to rewrite the code in KB article 316383 to
decrease the number of object references.
That's pretty bored :-)

I'm answering the post below, but I strongly suspect you already know
this stuff and have a typo someplace, or just got confused with
commenting and uncommenting lines in your test code.
This resulted in a number of nested With ... End With.

The original code had a

Dim r As Integer, c As Integer

shortly before a For Next.

The original code does not use With ... End With.

I ended up with, no pun intended, the code below. If the Dim statement is
moved into more deeply nested With ... End Withs, there are compile errors.
Looking that the original code, it only Dims r and c once. Then just
re-assigns them in the loop. The With Statements don't have much to do
with it. With-End With defines a statment block, as does For..Next, and
it's illegal for a declaration in a statement block to shadow a
declaration in an enclosing block.

<big snip, and moving some things around>
Dim r As Integer, c As Integer
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
With oWord
.Visible = True
Pos = .InchesToPoints(7)
.Documents.Add()
With .ActiveDocument
'Dim r As Integer, c As Integer ' This works
'Insert a paragraph at the beginning of the document.
With .Content
Dim r As Integer, c As Integer ' This fails
.InsertAfter(Text:="Heading 1")

Both the commented and the uncommented version fail for me. Both are
attempting to shadow the "Dim r as Integer" at the top of the code
snippet there. The original code declares 'r' and 'c' only once.

Are you sure your commented line above works if uncommented? I can't
duplicate this, and I suspect there's either been a copying error or I'm
not understanding your question. What exactly is the compile error
you're getting?

I've included the statement twice below. I've commented out the case that
does work, so you should see a compile error.

Ordinarily such statements should be at the beginning of the procedure.
I don't agree, but that's neither here nor there, and totally irrelevant.
Are there any restrictions for placing PROCEDURE level Dim declaration
statement?
Where are these documented?


The language spec is a good start. The section on statements is at:

http://msdn.microsoft.com/library/de...lrfvbspec8.asp



Nov 21 '05 #3
Yes, I was bored.
Trying not to think today, I'm scheduled to have oral surgery tomorrow.

One goal is to remove my foot from my mouth so "I'll have a leg to stand
on".

I'll post the actual VB .NET in a few minutes.

The error is reproducible here.

--
http://www.standards.com/; See Howard Kaikow's web site.
"Howard Kaikow" <ka****@standards.com> wrote in message
news:eA****************@TK2MSFTNGP10.phx.gbl...
I got bored today, so I decided to rewrite the code in KB article 316383 to decrease the number of object references.
This resulted in a number of nested With ... End With.

The original code had a

Dim r As Integer, c As Integer

shortly before a For Next.

The original code does not use With ... End With.

I ended up with, no pun intended, the code below. If the Dim statement is
moved into more deeply nested With ... End Withs, there are compile errors.
I've included the statement twice below. I've commented out the case that
does work, so you should see a compile error.

Ordinarily such statements should be at the beginning of the procedure.
Are there any restrictions for placing PROCEDURE level Dim declaration
statement?
Where are these documented?

Imports Microsoft.Office.Interop
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim oWord As Word.Application
Dim Pos As Double
Dim r As Integer, c As Integer
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
With oWord
.Visible = True
Pos = .InchesToPoints(7)
.Documents.Add()
With .ActiveDocument
'Dim r As Integer, c As Integer ' This works
'Insert a paragraph at the beginning of the document.
With .Content
Dim r As Integer, c As Integer ' This fails
.InsertAfter(Text:="Heading 1")
.Font.Bold = True
.Paragraphs(1).SpaceAfter = 24 '24 pt spacing after paragraph.
.InsertParagraphAfter()
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
'Insert a paragraph at the end of the document.
.InsertAfter(Text:="Heading 2")
.Paragraphs(1).SpaceAfter = 6
.InsertParagraphAfter()
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
.InsertAfter(Text:="This is a sentence of normal text. Now here is a
table:")
'Insert another paragraph.
.InsertParagraphAfter()
.Paragraphs(.Paragraphs.Count).Range.Font.Bold = False
.InsertParagraphAfter()
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
'Insert a 3 x 5 table, fill it with data, and make the first row
'bold and italic.
With .Tables.Add(.Bookmarks.Item("\endofdoc").Range, 3, 5)
With .Range
.ParagraphFormat.SpaceAfter = 6
.Font.Bold = False
End With
For r = 1 To 3
For c = 1 To 5
.Cell(r, c).Range.Text = "r" & r & "c" & c
Next
Next
With .Rows.Item(1).Range.Font
.Bold = True
.Italic = True
End With
End With
End With
With .Content
'Add some text after the table.
.Paragraphs(.Paragraphs.Count).Format.SpaceAfter = 24
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
.InsertParagraphAfter()
End With
With .Paragraphs(.Paragraphs.Count)
.SpaceAfter = 24
With .Range
.Text = "And here's another table:"
.Font.Bold = False
.InsertParagraphAfter()
End With
End With
'Insert a 5 x 2 table, fill it with data, and change the column widths.
With .Tables.Add(.Bookmarks.Item("\endofdoc").Range, 5, 2)
.Range.ParagraphFormat.SpaceAfter = 6
For r = 1 To 5
For c = 1 To 2
.Cell(r, c).Range.Text = "r" & r & "c" & c
Next
Next
With .Columns
.Item(1).Width = oWord.InchesToPoints(2) 'Change width of columns 1 & 2
.Item(2).Width = oWord.InchesToPoints(3)
End With
End With
'Keep inserting text. When you get to 7 inches from top of the
'document, insert a hard page break.
With .Content
.InsertParagraphAfter()
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
Do
.ParagraphFormat.SpaceAfter = 6
.InsertAfter("A line of text")
.InsertParagraphAfter()
.Collapse(direction:=Word.WdCollapseDirection.wdCo llapseEnd)
Loop While Pos >=
.Information(Word.WdInformation.wdVerticalPosition RelativeToPage)
.InsertBreak(Word.WdBreakType.wdPageBreak)
.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
.InsertAfter("We're now on page 2. Here's my chart:")
.InsertParagraphAfter()
End With
'Insert a chart and change the chart.
With .Bookmarks.Item("\endofdoc").Range.InlineShapes.Ad dOLEObject( _
ClassType:="MSGraph.Chart.8", FileName _
:="", LinkToFile:=False, DisplayAsIcon:=False)
With .OLEFormat.Object
.charttype = 4 'xlLine = 4
With .Application
.Update()
.Quit()
End With
End With
'If desired, you can proceed from here using the Microsoft Graph
'Object model to make additional changes to the
'chart.
.Width = oWord.InchesToPoints(6.25)
.Height = oWord.InchesToPoints(3.57)
End With
'Add text after the chart.
With .Content
.InsertParagraphAfter()
.InsertAfter("THE END.")
End With
End With
End With
oWord = Nothing
'All done. Close this form.
Me.Close()
End Sub
End Class

--
http://www.standards.com/; See Howard Kaikow's web site.

Nov 21 '05 #4
* "Howard Kaikow" <ka****@standards.com> scripsit:
See http://www.standards.com/VBNET/WhitherGoestDim.html


Maybe I don't get the point, but as far as I see you want to declare 'r'
and 'c' inside a 'With...End With' block and try to use it outside the
block. This doesn't work, which is documented behavior.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 21 '05 #6
On 2004-09-12, Howard Kaikow <ka****@standards.com> wrote:
See http://www.standards.com/VBNET/WhitherGoestDim.html


Maybe I'm just missing something, but there doesn't seem to be anything
particularly confusing there. The specs are crystal clear, and to my
mind at least, exactly what one would expect. The scope of a local
variable is from the point of declaration to the end of the current
statement block.

With..End With pairs constitute a statement block, as do For..Next
pairs.

Essentially what you have with your example is this...

**************************
With SomeVariable
Dim r as integer ' First declaration

With SomeOtherVariable
Dim r1 as integer ' Second declaration
r = 5
End With
' r1 is now out of scope

With AThirdVariable
r = 23 ' this is legal
r1 = 24 ' this is illegal
End With
End With
' r is now out of scope

r = 25 ' this is illegal

***************************

What do you feel is buggy about this, or what about it doesn't follow the
specification?

BTW, if you think this doesn't represent your long sample accurately, I
think you need to look at the sample again. r and c are definitely used
outside the scope of the second declaration. The second declaration
falls out of scope at line 111, but r and c are still being used at
lines 132-133. The first declaration (the one commented out in the
same) doesn't fall out of scope until line 179, that's why it works
fine.

One other thing, you actually don't need these declarations at all, you
can declare the variables within the loops, which give them the most
limited possible scope

For r AS Integer = 1 To 5
For c As Integer = 1 To 5
Next
Next

Nov 21 '05 #7
OK, so the constraint is With ... End.

--
http://www.standards.com/; See Howard Kaikow's web site.
"David" <df*****@woofix.local.dom> wrote in message
news:slrnck9fv0.nkh.df*****@woofix.local.dom...
On 2004-09-12, Howard Kaikow <ka****@standards.com> wrote:
See http://www.standards.com/VBNET/WhitherGoestDim.html


Maybe I'm just missing something, but there doesn't seem to be anything
particularly confusing there. The specs are crystal clear, and to my
mind at least, exactly what one would expect. The scope of a local
variable is from the point of declaration to the end of the current
statement block.

With..End With pairs constitute a statement block, as do For..Next
pairs.

Essentially what you have with your example is this...

**************************
With SomeVariable
Dim r as integer ' First declaration

With SomeOtherVariable
Dim r1 as integer ' Second declaration
r = 5
End With
' r1 is now out of scope

With AThirdVariable
r = 23 ' this is legal
r1 = 24 ' this is illegal
End With
End With
' r is now out of scope

r = 25 ' this is illegal

***************************

What do you feel is buggy about this, or what about it doesn't follow the
specification?

BTW, if you think this doesn't represent your long sample accurately, I
think you need to look at the sample again. r and c are definitely used
outside the scope of the second declaration. The second declaration
falls out of scope at line 111, but r and c are still being used at
lines 132-133. The first declaration (the one commented out in the
same) doesn't fall out of scope until line 179, that's why it works
fine.

One other thing, you actually don't need these declarations at all, you
can declare the variables within the loops, which give them the most
limited possible scope

For r AS Integer = 1 To 5
For c As Integer = 1 To 5
Next
Next


Nov 21 '05 #8
It's clear.

As I said in an earlier post, I was trying not to think today, due to the
scheduled oral surgery tomorrow.
This posting is sufficient proof that I succeeded as it is clear that I was
not thinking.

--
http://www.standards.com/; See Howard Kaikow's web site.
"David" <df*****@woofix.local.dom> wrote in message
news:slrnck9fv0.nkh.df*****@woofix.local.dom...
On 2004-09-12, Howard Kaikow <ka****@standards.com> wrote:
See http://www.standards.com/VBNET/WhitherGoestDim.html


Maybe I'm just missing something, but there doesn't seem to be anything
particularly confusing there. The specs are crystal clear, and to my
mind at least, exactly what one would expect. The scope of a local
variable is from the point of declaration to the end of the current
statement block.

With..End With pairs constitute a statement block, as do For..Next
pairs.

Essentially what you have with your example is this...

**************************
With SomeVariable
Dim r as integer ' First declaration

With SomeOtherVariable
Dim r1 as integer ' Second declaration
r = 5
End With
' r1 is now out of scope

With AThirdVariable
r = 23 ' this is legal
r1 = 24 ' this is illegal
End With
End With
' r is now out of scope

r = 25 ' this is illegal

***************************

What do you feel is buggy about this, or what about it doesn't follow the
specification?

BTW, if you think this doesn't represent your long sample accurately, I
think you need to look at the sample again. r and c are definitely used
outside the scope of the second declaration. The second declaration
falls out of scope at line 111, but r and c are still being used at
lines 132-133. The first declaration (the one commented out in the
same) doesn't fall out of scope until line 179, that's why it works
fine.

One other thing, you actually don't need these declarations at all, you
can declare the variables within the loops, which give them the most
limited possible scope

For r AS Integer = 1 To 5
For c As Integer = 1 To 5
Next
Next


Nov 21 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2360
by: oom | last post by:
I am a bit of a newbie when it comes to python, when working with lists today I noticed some very odd behaviour, any suggestions welcome: Python 2.2.3 (#1, Nov 6 2003, 14:12:38) on linux2...
30
3381
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then...
8
2509
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined...
51
3879
by: Tony Sinclair | last post by:
I'm just learning C#. I'm writing a program (using Visual C# 2005 on WinXP) to combine several files into one (HKSplit is a popular freeware program that does this, but it requires all input and...
2
3497
by: Jim M | last post by:
I rarely deal with recordsets directly with code, since I usually use Access queries, so be patient with this question. I want to open a recordset with various default variables used by my program....
27
1859
by: SamJs | last post by:
WITH (this) { a = 5 } I'm finding that this.a = 5 will come from this expression. I would have thought that the search for a would come up undefined and leave it at that. Is JavaScript...
55
6150
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
0
35188
MMcCarthy
by: MMcCarthy | last post by:
We often get questions on this site that refer to the scope of variables and where and how they are declared. This tutorial is intended to cover the basics of variable scope in VBA for MS Access. For...
162
10065
by: Sh4wn | last post by:
Hi, first, python is one of my fav languages, and i'll definitely keep developing with it. But, there's 1 one thing what I -really- miss: data hiding. I know member vars are private when you...
0
7091
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7342
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6998
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7464
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5586
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5018
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
1516
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
391
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.