Vba word no spacing

  • Remove From My Forums
  • Question

  • Hello all Experts,

    How can I change line and paragraph spacing using vba?

    Using VBA I would like to create several macros.
    1. to increase line spacing of selected text by the smallest possible
    amount.
    2. the same to decrease line spacing.
    3. to increase paragraph spacing of selected paragraphs
    4. same to decrease paragraph spacing.

Answers

  • «moishy» wrote in message news:581f9774-00f3-41d3-a6db-8ceee96efcfd@communitybridge.codeplex.com…

    Thank you Mike for giving attention for my question.

    I’m aware that I can record a macro, but there are at least two limitations I can think of that will render that option pointless.

    a. I can’t record a macro to adjust the paragraph spacing (i.e. nothing is recorded).

    b. Recording a macro for the line spacing, I will have to hard code the change (for example: Selection.ParagraphFormat.LineSpacing LinesToPoints(1.15)). I need it to increase or decrease by the smallest possible option every time the macro is ran.


         

    For what you want to do, the macro recorder is definitely not the way to go. For Spacing Before, you’ll need something along these lines:

    Sub IncreaseSpacingBefore()

    On Error GoTo errhandler

    Selection.ParagraphFormat.SpaceBefore = _
    Selection.ParagraphFormat.SpaceBefore + 1

    Exit Sub

    errhandler:

    Selection.ParagraphFormat.SpaceBefore = 6 ‘or the value you prefer

    Sub DecreaseSpacingBefore()
    On Error GoTo errhandler
    Selection.ParagraphFormat.SpaceBefore = _
    Selection.ParagraphFormat.SpaceBefore — 1
    Exit Sub

    errhandler:

    Selection.ParagraphFormat.SpaceBefore = 6 ‘or the value you prefer

    End Sub

    A similar couple of macros can easily be created for Spacing After. I have set the increment to 1 point but you can change that if you want to. As far as the line spacing is concerned, you will have to decide if you want variable or fixed line spacing,
    before starting to code.


    Stefan Blom, Microsoft Word MVP

    • Edited by

      Tuesday, February 14, 2012 7:42 PM
      (typo)

    • Marked as answer by
      moishy
      Wednesday, February 15, 2012 7:49 AM

  • «moishy» wrote in message news:6d3bb4ea-c6df-4f2a-82a8-ccb4a45a53b1@communitybridge.codeplex.com…

    I’m not sure what you mean. I would like the macro to detect the font size and set the spacing to double that value.


    OK, that’s simple, at least in theory. You could look at the font size of the first character, say, in the paragraph and use that as a starting point:

    Sub SetFixedLineSpacingInPara()

    With Selection.ParagraphFormat

    .LineSpacingRule = wdLineSpaceExactly

    .LineSpacing = 2 * Selection.Characters(1).Font.Size

    End With

    End Sub

    In practice, the font size can vary within a paragraph. You can avoid this possible issue by resetting the font properties for all text in the selection or by looping all characters to find out which is the largest font present in the selection.


    Stefan Blom, Microsoft Word MVP

    • Marked as answer by
      moishy
      Wednesday, February 15, 2012 7:49 AM

  • Hi Moishy,

    As a general rule, changes to paragraph attributes should be done by changing the underlying Styles, not be direct formatting. However, as it seems you may be doing this to manage the page composition, perhaps there’s a valid reason in this case.

    Below are some macros to adjust both the line spacing and paragraph-before spacing, by 0.5pt increments. The same kind of thing can be done with the paragraph-after spacing I’ve also tossed in a couple more you might like to play with, for adjusting
    the character spacing and scaling.

    Sub IncreaseParaSpaceBefore()
    On Error Resume Next
    With Selection.ParagraphFormat
      .SpaceBefore = .SpaceBefore + 0.5
    End With
    End Sub

    Sub DecreaseParaSpaceBefore()
    On Error Resume Next
    With Selection.ParagraphFormat
      .SpaceBefore = .SpaceBefore — 0.5
    End With
    End Sub

    Sub IncreaseLineSpace()
    On Error Resume Next
    With Selection.ParagraphFormat
      .LineSpacing = .LineSpacing + 0.5
    End With
    End Sub

    Sub DecreaseLineSpace()
    On Error Resume Next
    With Selection.ParagraphFormat
      .LineSpacing = .LineSpacing — 0.5
    End With
    End Sub

    Sub IncreaseCharSpace()
    On Error Resume Next
    With Selection.Font
      .Spacing = .Spacing + 0.05
    End With
    End Sub

    Sub DecreaseCharSpace()
    On Error Resume Next
    With Selection.Font
      .Spacing = .Spacing — 0.05
    End With
    End Sub

    Sub IncreaseCharScale()
    On Error Resume Next
    With Selection.Font
      .Scaling = .Scaling — 1
    End With
    End Sub

    Sub DecreaseCharScale()
    On Error Resume Next
    With Selection.Font
      .Scaling = .Scaling — 1
    End With
    End Sub


    Cheers
    Paul Edstein
    [MS MVP — Word]

    • Marked as answer by
      moishy
      Wednesday, February 15, 2012 7:49 AM

how to check MS Word paragraph line spacing using vba script.
here is code where line spacing are change in paragraph(1).
we add paragraph(1) line space 2.
now how can we get it if we give same paragraph(1) and its gives us 2.

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Sep 11, 2018 at 12:16

Umair Khan's user avatar

4

To check line spacing: Selection.ParagraphFormat.LineSpacing

Te increase line spacing Selection.ParagraphFormat.LineSpacing = .LineSpacing + 1

Te decrease line spacing Selection.ParagraphFormat.LineSpacing = .LineSpacing - 1

thanks.

answered Sep 17, 2018 at 15:23

Khurshid Alam's user avatar

Record a macro where you change the line setting and then look at the result you get.

If there is any keyword you don’t understand put the cursor on it and press F1, this will bring up the MS Help page for that keyword.

To record a macro you need to have the Developer Tab enabled.

answered Sep 11, 2018 at 14:03

freeflow's user avatar

freeflowfreeflow

4,0933 gold badges10 silver badges17 bronze badges

What do you mean by «setup»?

The fact of the matter is, you ARE using styles. Even when you manually make format changes to a paragraph. Every single paragraph in Word has a style attached to it. Without exception. You can not have any text, any paragraph, without a style attached to it.

Why not take control and make them YOUR styles?

The advantages of using styles properly is huge. Format is consistent. You never have to use those empty paragraphs. You can globally change ALL paragraphs using a style by simply changing the style.

Say you have a 10 page document, and it has 40 instances of a specifically formatted paragraph. Say quotes that are formatted as indented 1.5 inches, italics and 11 pts.

Say you decide that you want the format to be 12 pts.

Choice A — There is no explicit style attached — Word has it as that dumb Normal + yadda yadda crap.

Action required: manually go through the document, selecting each of the 40 instances, and changing the font size to 12.

Choice B — the paragraphs have MyQuote style attached.

Actions required: ONE action is required. Modify the style to 12 pts.

Using the same example, but now you decide you want those quotes to be indented 2.2 inches, and the Font changed to Arial.

Choice A: selecting each of the 40 instances and use TWO separate dialogs (Format > Font — to change the font, and Format > Paragraph to change the indent).

Choice B: Modify the style.

Making, creating, Styles is not hard.

As far as I’m concerned, if every single document you ever make is unique, totally unique, — then OK, forget about styles.

But if you ever make a document even similar, use a template and in the template use Styles.

When you do use styles, processing is much easier in VBA.[vba]Dim oPara As Paragraph
For Each oPara In ActiveDocument.Paragraphs
If oPara.Style = «ThisStyle» Then
oPara.Style = «ThatStyle»
End If
Next[/vba]Boom. Done. You change the format of every instance.

Real world example — and I have used this in development of templates.

Say you have — let’s make it simple — a single page. It has four headings followed by body text. The body text is Times Roman 11 pts indented 1.5 inches, and you are wondering if it would be better if it was Arial 12 pts, and indented a wee bit more.

Style «BodyTextA» — Times Roman, 11 pts, indent 1.5 «
Style «BodyTextB» — Arial, 12 pts, indent 1.8″

[vba]Dim oPara As Paragraph
For Each oPara In ActiveDocument.Paragraphs
Select Case oPara.Style
Case «BodyTextA»
oPara.Style = «BodyTextB»
Case «BodyTextB»
oPara.Style = «BodyTextA»
End Select
Next[/vba]Put up as a macro button on a toolbar, I can click the button and watch the text switch back and forth. I can see EASILY (one click — it toggles) what the document format would look like with the different attributes. Again, changing them manually would require going through two separate dialogs — Format > Font, and Format > Paragraph.

Just think, suppose you were using a border….ANOTHER dialog to go through.

Suppose you were using bullets….ANOTHER dialog to go through.

I guess my point is that yes, I will grant you that using Styles can take some initial effort. However, once you get the hang of using them, in the long run they make using Word much easier.

Again, I am not sure what you mean by «setup». Creating styles is not difficult at all.

**Hey, it’s Chris here! The following is a guest post by a fellow VBA blogger named Ryan Wells who has some great macro code posted to his website.  I want to give a special thanks to Ryan for taking the time to share with the TSG community and provide us with some awesome code. Take it away Ryan!

What This VBA Code Does

To some, nothing makes their blood boil quite like two spaces after a period. People are passionate about their character spacing. I’ve witnessed some pretty heated arguments about whether you should have one space or two spaces following a punctuation mark.

I admit, I once was a longtime member of the «two-spaces-after-a-period» camp, but my Public Relations wife pointed out how horribly wrong I was. Truth is, the practice of adding two spaces after a period dates back to the days of 1950s-era monospaced manual typewriters. In today’s world of proportional fonts, a single space is preferred.

This VBA macro replaces all those annoying double spaces in your Word document with single spaces and lets you know how many replacements the macro made.

Sub ReplaceDoubleSpaces()
‘PURPOSE: Replace all double spaces in the active document with single
‘         spaces and report the number of instances replaced.
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
‘AUTHOR: Ryan Wells (wellsr.com)

Dim Org_Count As Double
Dim New_Count As Double
Dim Replacements As Double

Application.ScreenUpdating = False

‘Count the original number of characters (for report out)
  Org_Count = ActiveDocument.Characters.Count

‘Find/Replace double spaces with single spaces
  With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = Space(2)
    .Replacement.Text = Space(1)
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
  End With

   ‘Count the final number of characters
  New_Count = ActiveDocument.Characters.Count

‘Calculate number of replacements
  Replacements = Org_Count — New_Count

‘Report results
  If Replacements = 0 Then
    MsgBox «No double spaces found in document.», _
      vbInformation, «Replace Double Space»
  Else
    MsgBox «Replacing » & Replacements & » double space(s) with single space(s).», _
      vbInformation, «Replace Double Space»
  End If

Application.ScreenUpdating = True

End Sub

About The Author

Ryan Wells is a nuclear engineer by day and a VBA developer by night. He set out to automate many of his complex nuclear engineering tasks using VBA with the goal of reducing errors and increasing efficiency. Ryan now publishes his VBA code examples and macro tutorials from Excel, Outlook, Word, and more to inspire other office workers to do the same with their jobs. If you like what you see, check out Ryan’s VBA Tutorials Blog .

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

  • #1

Hi,

I have an application that (through VBA) opens an existing excel workbook and puts it into a Word document. This works just fine. But, since I have just recently converted to Office 2007 I find that the line spacing in 2007 is bigger than previous Word. I recorded a macro inside Word 2007 to make the spacing 1 line. This is what the recorder showed:

WordBasic.OpenOrCloseParaBelow

I stuck this inside the current macro I have that creates the Word document from Excel, but nothing happened. It didn’t give an error and it didn’t change the spacing. I think it is because I did not have anything selected inside the document. This is actually a table inside Word. How do I select the document (table) through VBA in order for this spacing command to work?

Thanks for any examples.

Nancy

Difference between two dates

Secret function! Use =DATEDIF(A2,B2,»Y»)&» years»&=DATEDIF(A2,B2,»YM»)&» months»&=DATEDIF(A2,B2,»MD»)&» days»

  • #2

OK — here is the two lines that I needed.

wrdApp.Selection.WholeStory
WordBasic.OpenOrCloseParaBelow

Hope this helps someone else.

: )

Like this post? Please share to your friends:
  • Vba word if text not found
  • Vba word if exists
  • Vba word if else if
  • Vba word find wrap
  • Vba word find highlight