Vba word переход на новую строку

Ksenya100

72 / 64 / 3

Регистрация: 13.05.2010

Сообщений: 349

1

25.03.2011, 18:20. Показов 17694. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

подскажите пожалста!!
в макросе прописываю перенось строки

PureBasic
1
ls_text = ls_text & vbCr & "ну и тут что-то не важно"

и в документе вместо переноса строки
появляются символы — маленькие квадратики со знаком вопроса внутри

(вместо vbCr писала vbCrLf…тож самое)

я вообще не очень про это знаю

подскажите, что писать надо!!



0



72 / 64 / 3

Регистрация: 13.05.2010

Сообщений: 349

29.03.2011, 18:52

 [ТС]

2

как выход — написала на новой строке новую переменную



0



Частенько бываю

749 / 330 / 42

Регистрация: 20.06.2007

Сообщений: 854

30.03.2011, 04:35

3

Используйте константы VB, например vbNewLine



0



72 / 64 / 3

Регистрация: 13.05.2010

Сообщений: 349

30.03.2011, 17:17

 [ТС]

4

Vlanib, попробовала
сейчас попытаюсь описать что получилось:
у меня в шаблоне (word) стоит переменная (которая должна быть в 2 строки)
если после нее есть пустая строка, то vbnewline срабатывает но естественно остается и пустая строка
вот так получается:

Код

название
дата
//пустая строка, которая мне не нужна

а если после docvariable строка содержит текст (опять же в шаблоне) (а именно так мне и надо) то «дата» на новую строку не переносится

что делать????



0



0 / 0 / 0

Регистрация: 14.11.2017

Сообщений: 7

10.06.2011, 13:51

5

Цитата
Сообщение от Ksenya100
Посмотреть сообщение

Vlanib, попробовала
сейчас попытаюсь описать что получилось:
у меня в шаблоне (word) стоит переменная (которая должна быть в 2 строки)
если после нее есть пустая строка, то vbnewline срабатывает но естественно остается и пустая строка
вот так получается:

Код

название
дата
//пустая строка, которая мне не нужна

а если после docvariable строка содержит текст (опять же в шаблоне) (а именно так мне и надо) то «дата» на новую строку не переносится

что делать????

пиши так:
название & Chr(11) & дата

и будет тебе счастье…



0



72 / 64 / 3

Регистрация: 13.05.2010

Сообщений: 349

16.01.2012, 10:59

 [ТС]

6

Zarubin, да, дейстаительно всё получилось, спасибо !!



0



New paragraph / new line?

In Microsoft Word, there’s all the difference in the world between a new paragraph and a new line.

To insert a new paragraph, press the Enter key. If you have «show all characters» turned on, you’ll see each paragraph break with its «backwards P» icon. Each paragraph in Word has its own properties. It can have extra space above or below, it could be indented from the left / right margins, with the option of different indentation for the first line.

To insert a new line, press Shift + Enter. If you have «show all characters» turned on, you’ll see each manual line break with the icon of a solid arrow that goes first down, then left. Forcing a new line does not start a new paragraph, so the text will be laid out exactly as if it were a continuation of the paragraph you were in, simply on a new line. Because that’s what it is. If your paragraph has extra space above or below, this new line will simply be spaced in the same way as the line-spacing (you don’t get the extra spacing). If your paragraph has different indentation for the first line, this new line won’t have that different indentation, because it’s not the first line in a new paragraph.

That’s how you enter a line break in Word itself. But what if you want to do so in Visual Basic (i.e., in a macro)?

I needed to do this recently, and the answer was hard to find online, so I’ll write it up here — as usual, to help me find this again, and to help anyone else looking for the same thing.

New paragraphs in VBA are easy. There’s an application wide constant defined, vbCrLf, which represents ASCII character 10 (carriage return) followed by ASCII character 13 (line feed). A code snippet like this:

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbCrLf & "Bar"

will replace the text of that paragraph with «Foo», followed by a paragraph break, followed by «Bar». Thus:

Foo and Bar in different paragraphs

But how do you get «Foo», followed by a line break, followed by «Bar», using VBA?

Foo and Bar separated by a line break

You might try some other VBA supplied constants. Such as vbCr (carriage return, ASCII 13) and vbNewLine (new line, also ASCII 13), or vbLf (line feed, ASCII 10). But all of those insert a new paragraph.

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbCr & "Bar"
ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbLf & "Bar"
ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbNewLine & "Bar"

It turns out that what you need is ASCII 11, for which there is no pre-defined constant. The following gives you what you’re after:

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & Chr(11) & "Bar"

I didn’t find that in any Microsoft documentation anywhere, but it works. Thanks for reading, and happy macro writing!

  • Remove From My Forums
  • Question

  • I tried «rn» with no look. It simply inserts «rn» verbatim into the document. How do I send a newline character in VBA?

    Thanks!

    Sep

Answers

  • Sub ScratchMacro()
    ‘A quick macro scratch pad created by Greg Maxey
    ActiveDocument.Range.InsertAfter «Test» & Chr(11) & «Test»  ‘New line
    ActiveDocument.Range.InsertAfter «Test» & vbCr & «Test» ‘New paragraph
    End Sub

    «Sepoto» wrote in message news:9bff0bf2-f53d-4c04-97fa-f5b48a48e120@communitybridge.codeplex.com…

    I tried «rn» with no look. It simply inserts «rn» verbatim into the document. How do I send a newline character in VBA?

    Thanks!

    Sep


    Greg Maxey Please visit my website at: http://gregmaxey.mvps.org/word_tips.htm

    • Marked as answer by

      Wednesday, October 27, 2010 10:57 PM

  • Remove From My Forums
  • Question

  • Hi VBA folks

    I am trying to code a little macro which is giving me a hard time coding it the right way, this are the things I have to do:

    1) Insert a  new section at the end of the document

    2)type the first sentence of each section on separate lines in the newly added section

    for this I pieced together the following code:

    ActiveDocument.Sections.Add Start:=wdSectionNewPage
    
    For Each ss In ActiveDocument.Sections
        ActiveDocument.Sections(ActiveDocument.Sections.count).Range.Text = ss.Range.Sentences(1).Range.Text
       Selection.MoveDown unit:=wdLine, count:=3, Extend:=wdMove
    Next ss
    

    however, it seems like word is just overriding the text on the same line and not moving down a given number of lines to type the next paragraph

    I know that the problem is within the following part, could someone please help me correct this. thanks so much guys

    Selection.MoveDown unit:=wdLine, count:=3, Extend:=wdMove<br/>
    

Answers

    • Proposed as answer by

      Saturday, January 28, 2012 4:04 AM

    • Marked as answer by
      danishani
      Wednesday, February 1, 2012 5:05 AM
  • Use:

    Selection.EndKey wdStory
    Selection.InsertBreak wdSectionBreakNextPage
    With ActiveDocument
        With .Sections(.Sections.Count).Range
            For i = 1 To ActiveDocument.Sections.Count — 1
                .InsertAfter ActiveDocument.Sections(i).Range.Sentences(1).Text & vbCr
            Next i
        End With
    End With


    Doug Robbins — Word MVP dkr[atsymbol]mvps[dot]org

    • Proposed as answer by
      danishani
      Saturday, January 28, 2012 4:04 AM
    • Marked as answer by
      danishani
      Wednesday, February 1, 2012 5:05 AM

Home / VBA / How to Add a New Line (Carriage Return) in a String in VBA

In VBA, there are three different (constants) to add a line break.

  1. vbNewLine
  2. vbCrLf
  3. vbLf

vbNewLine

vbNewLine inserts a newline character that enters a new line. In the below line of code, you have two strings combined by using it.

Range("A1") = "Line1" & vbNewLine & "Line2"

When you run this macro, it returns the string in two lines.

It returns the character 13 and 10 (Chr(13) + Chr(10)). You can use a code in the following way as well to get the same result.

Range("A1") = "Line1" & Chr(13) & Chr(10) & "Line2"

But when you use vbNewLine you don’t need to use CHAR function.

vbCrLf

vbCrLf constant stands for Carriage Return and Line feed, which means Cr moves the cursor to the starting of the line, and Lf moves the cursor down to the next line.

When you use vbCrLf within two string or values, like, you have in the following code, it inserts a new line.

Range("A1") = "Line1" & vbCrLf & "Line2"

vbLf

vbLf constant stands for line feed character, and when you use it within two strings, it returns line feed character that adds a new line for the second string.

Range("A1") = "Line1" & vbLf & "Line2"

If you want to add a new line while using the VBA MsgBox you can use any of the above three constants that we have discussed.

MsgBox "Line1" & vbNewLine & "Line2"
MsgBox "Line1" & vbCrLf & "Line2"
MsgBox "Line1" & vbLf & "Line2"

There’s also a constant vbCr that returns carriage return character that you can use to insert a new line in a message box.

MsgBox "Line1" & vbCr & "Line2"

vbCr won’t work if you want to enter a cell value until you apply wrap text to it.

Понравилась статья? Поделить с друзьями:
  • Vba word переместить курсор
  • Vba word перейти в начало документа
  • Vba word номер абзаца
  • Vba word нет календаря
  • Vba word неразрывный пробел