Textbox in word vba

Add TextBox

This macro will add a TextBox to the active Word document:

Sub AddTextBox()
ActiveDocument.Shapes.AddTextBox Orientation:=msoTextOrientationHorizontal, Left:=1, Top:=1, Width:=300, Height:=100
End Sub

Delete TextBox

This VBA macro will delete the first TextBox in the active document:

Sub DeleteTextBox()
'deletes first text box in activedoc
'not straithforward because its not easy to identify text boxes
    Dim oShape As Shape
    If ActiveDocument.Shapes.Count > 0 Then
        For Each oShape In ActiveDocument.Shapes
            If oShape.AutoShapeType = msoShapeRectangle Then 'we need to check both if oShape is of type msoShapeRectangle and its textframe contains place for writing
                If oShape.TextFrame.HasText = True Then
                    oShape.Delete
                End If
            End If
        Next oShape
    End If
End Sub

Write in TextBox

This Word macro uses similar methodology to write to the first TextBox in the active document:

Sub WriteInTextBox()
'writes into first text box in active doc
Dim oShape As Shape
    If ActiveDocument.Shapes.Count > 0 Then
        For Each oShape In ActiveDocument.Shapes
            If oShape.AutoShapeType = msoShapeRectangle Then 'we need to check both if oShape is of type msoShapeRectangle and its textframe contains place for writing
                If oShape.TextFrame.HasText = True Then
                    oShape.TextFrame.TextRange.InsertAfter "https://www.automateexcel.com/vba-code-library"
                    Exit For 'we just want to write into first textbox
                End If
            End If
        Next oShape
    End If
End Sub

Microsoft Word Create Text Box using VBA (Visual Basic for Applications)

CreateTextbox

Creates a default size of textbox around the selection in a document. In this article we will write a code with example which will put a textbox around the selected text along with certain formatting. For example refer the below screenshot which has selection to a formatted line of text:

Code example

Sub CreateTextBoxCodeExample()
        
    'Bind selection
    Dim objSelection As Selection
    Set objSelection = Selection
    
    'Check selection type
    If objSelection.Type = wdSelectionNormal Then
        'Create text box
        objSelection.CreateTextBox
        
        'Declare shape range object to hold the shape range
        Dim oShapeRange As ShapeRange
        
		'Bind reference
        Set oShapeRange = objSelection.ShapeRange
        
        'Perform formatting
        oShapeRange.BackgroundStyle = msoBackgroundStylePreset7
        objSelection.ShapeRange(1).Line.DashStyle = msoLineDashDot
        
        'Memory cleanup
        Set oShapRange = Nothing
    End If
    
    'Memory cleanup
    Set objSelection = Nothing
End Sub

Output

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Old

04-02-2016, 04:16 AM

rpb925
rpb925 is offline

Insert and Filling Textbox using VBA Windows 7 64bit Insert and Filling Textbox using VBA Office 2010 64bit

Novice

Insert and Filling Textbox using VBA

 

Join Date: Mar 2016

Location: Sydney

Posts: 17

rpb925 is on a distinguished road

Default

Insert and Filling Textbox using VBA



I assume this is straight forward but it isn’t really happening for me. I want to:

Add a Text Box to the Right hand Side and have written vertically the word MEMO font size 48 Arial in grey. I have been working from a few things online but to no avail. I am running the code from access in a newly created word document. It always comes up specified value is out of Range and it’s starting to get repetitive. Any help is appreciated. P.S I realise I haent added text yet and the box is too small but I haven’t gotten that far yet…

Code:

Sub Textbox()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdShp As Word.Shape
Set wdApp = CreateObject("Word.Application")
    
With wdApp
.Visible = True
.ScreenUpdating = False

Set wdDoc = .Documents.Add

    With wdDoc
    Set wdShp = .Shapes.AddTextbox(Orientation:=msoTextOrientationVertical, Left:=10, Top:=10, Width:=10, Height:=10)
    End With
 
.ScreenUpdating = True

End With

Set wdDoc = Nothing: Set wdApp = Nothing: Set wdShp = Nothing

End Sub

Reply With Quote

Old

04-02-2016, 04:58 AM

Default


Maybe something like:

Code:

Sub Textbox()
Dim wdApp As Object
Dim wdDoc As Object
Dim wdShp As Object
Dim oRng As Object
    On Error Resume Next
    Set wdApp = GetObject(, "Word.Application") 'It is always faster to get the running Word if available
    If Err Then
        Set wdApp = CreateObject("Word.Application")
    End If
    On Error GoTo 0
    With wdApp
        .Visible = True
        .ScreenUpdating = False

        Set wdDoc = wdApp.Documents.Add
        Set wdShp = wdDoc.Shapes.AddTextbox(Orientation:=msoTextOrientationUpward, _
                                            Left:=10, _
                                            Top:=10, _
                                            Width:=wdApp.CentimetersToPoints(1.25), _
                                            Height:=wdApp.CentimetersToPoints(10))
        With wdShp
            Set oRng = .TextFrame.TextRange
            With oRng
                .Text = "This is the text box text"
                .Font.Name = "Times New Roman"
                .Font.Size = 14
                .Font.Italic = True
                .ParagraphFormat.Alignment = 1 'Centred
            End With
        End With
        .ScreenUpdating = True
    End With
lbl_exit:
    Set wdDoc = Nothing: Set wdApp = Nothing: Set wdShp = Nothing
    Exit Sub
End Sub

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Old

04-02-2016, 05:11 AM

gmaxey
gmaxey is offline

Insert and Filling Textbox using VBA Windows 7 32bit Insert and Filling Textbox using VBA Office 2010 (Version 14.0)

Word MVP 2003-2009

 

Join Date: May 2010

Location: Brasstown, NC

Posts: 1,250

gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough

Default


The following runs fine when run from within Word. What line of your code is throwing the error?

Code:

Sub Textbox()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdShp As Word.Shape
 'Set wdApp = CreateObject("Word.Application")
 With Application
    .Visible = True
    .ScreenUpdating = False
    Set wdDoc = .Documents.Add
    Set wdShp = wdDoc.Shapes.AddTextbox(Orientation:=msoTextOrientationVertical, Left:=10, Top:=10, Width:=70, Height:=200)
    With wdShp.TextFrame
      .TextRange = "MEMO"
      .TextRange.Font.Name = "Arial"
      .TextRange.Font.Size = "48"
    End With
    .ScreenUpdating = True
  End With
  Set wdDoc = Nothing: Set wdShp = Nothing
End Sub

Reply With Quote

Old

04-02-2016, 05:48 AM

rpb925
rpb925 is offline

Insert and Filling Textbox using VBA Windows 7 64bit Insert and Filling Textbox using VBA Office 2010 64bit

Novice

Insert and Filling Textbox using VBA

 

Join Date: Mar 2016

Location: Sydney

Posts: 17

rpb925 is on a distinguished road

Default


It seems like it doesn’t like the AddTextbox Command it keeps coming up with following Error Run-time eror ‘-2147024809(80070057) The Specified value is out of range. I’ve copy and pasted the vba into a macro in word and it runs like a charm. I believe it is something to do with running the addTextbox from Access that is flipping it out.
If you have access I assume you’ll get the same error. Not sure if I have to set the variable as something other than a «as Word.Shape»

PS Thanks Graham for the tip on running already open word application will try it out!!

Reply With Quote

Old

04-02-2016, 06:14 AM

gmaxey
gmaxey is offline

Insert and Filling Textbox using VBA Windows 7 32bit Insert and Filling Textbox using VBA Office 2010 (Version 14.0)

Word MVP 2003-2009

 

Join Date: May 2010

Location: Brasstown, NC

Posts: 1,250

gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough

Default


I would assume you hare using early binding and ave a reference to the Word Object module set in your project. I used late binding as shown and it worked without issue from Access 2016:

Code:

Sub Textbox()
Dim wdApp As Object
Dim wdDoc As Object
Dim wdShp As Object
Set wdApp = CreateObject("Word.Application")
  With wdApp
    .Visible = True
    .ScreenUpdating = False
    Set wdDoc = .Documents.Add
    With wdDoc
      Set wdShp = .Shapes.AddTextbox(Orientation:=5, Left:=10, Top:=10, Width:=10, Height:=10)
    End With
   .ScreenUpdating = True
  End With
  Set wdDoc = Nothing: Set wdApp = Nothing: Set wdShp = Nothing
End Sub

Reply With Quote

Old

04-02-2016, 02:35 PM

rpb925
rpb925 is offline

Insert and Filling Textbox using VBA Windows 7 64bit Insert and Filling Textbox using VBA Office 2010 64bit

Novice

Insert and Filling Textbox using VBA

 

Join Date: Mar 2016

Location: Sydney

Posts: 17

rpb925 is on a distinguished road

Talking


Legendary. It was the text direction command it was tripping on. Once replaced with msoTextDirection with a numerical value as you did it works well. Definitely would not have worked that one out on my own. It seems to run both as a Object and Word.Shape with no issues.
Thanks Greg.
Appreciate it.

Reply With Quote

I created a text bo in the Word and I would like to insert text into it:

Sub k()
Dim Box As Shape
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=50, Top:=50, Width:=100, Height:=100)
//HOW TO INSERT HERE TEXT INTO TEXT BOX


End Sub

Deduplicator's user avatar

Deduplicator

44.3k7 gold badges65 silver badges115 bronze badges

asked Jun 15, 2013 at 18:12

Yoda's user avatar

Here is the solution:

Sub k()
    Dim Box As Shape
    Set Box = ActiveDocument.Shapes.AddTextbox( _
        Orientation:=msoTextOrientationHorizontal, _
        Left:=50, Top:=50, Width:=100, Height:=100)

        'The solution for you:
        Box.TextFrame.TextRange.Text = "My text comes this way"

End Sub

answered Jun 15, 2013 at 18:19

Kazimierz Jawor's user avatar

Kazimierz JaworKazimierz Jawor

18.8k7 gold badges35 silver badges55 bronze badges

7

Тогда так: Предположим что у нас есть документ Word 2007 который нужно без участия пользователя сохранить в формат PDF, TIFF, JPEG, PNG, PCX, DCX, GIF или BMP.

Скачиваем и устанавливаем Universal Document Converter (описание установки в txt файле — скажите файлообменик выложу туда)

в Word 2007 нажимаем записать макрос и жмем:

печать — печать и выбираем принтер «Universal Document Converter» после чего нажимаем кнопку свойства.

В открывшимся меню:
нажимаем слева «загрузить настройки» и выбираем нужный формат
потом жмем слева «пост-обработка» устанавливаем Отключена
далее «файлы и папки» — прописываем путь, и имя файла (если имя такое же как у открытого документа то пишим в поле имя файла &[DocName(0)].&[ImageType])
водный знак — отключен
обработка страниц — отключено (это обрезка по тексту)
параметры страницы — по усмотрению
нажимаем ок (можно сохранить настройки слева)

нажимаем еще раз ОК и дождавшись файла в указанной папке останавливаем запись макроса.

Полученный код из макроса вставляем в код программы.

для открытия или создания нового документа Word 2007 использовала это:

Visual Basic
1
2
3
4
5
Set WordApp = New Word.Application 'создаём  новый экземпляр Word-a
WordApp.Visible = True 'определяем видимость Word-a где True - видимый, а False - не видимый (работает только ядро)
'Set DocWord = WordApp.Documents.Add 'создаём новый документ в Word-e
Set DocWord = WordApp.Documents.Open("D:Distribotchet4.doc") 'если нужно открыть имеющийся документ, то пишем такой код
'DocWord.Activate 'активируем его

для закрытия документа без сохранения:

Visual Basic
1
2
DocWord.Close True 'закрываем документ без сохранения
WordApp.Quit True 'закрываем word 2007

у меня код макроса получился такой: принтер «Universal Document Converter» не установлен по умолчанию!

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub Макрос2()
'
' Макрос2 Макрос
'
' Печать на вирт принтер в Jpeg без вопросов и прогресса
    ActivePrinter = "Universal Document Converter"
    Application.PrintOut FileName:="", Range:=wdPrintAllDocument, Item:= _
        wdPrintDocumentContent, Copies:=1, Pages:="", PageType:=wdPrintAllPages, _
        ManualDuplexPrint:=False, Collate:=True, Background:=True, PrintToFile:= _
        False, PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
        PrintZoomPaperHeight:=0
End Sub

Ну вроде все =) если что спрашивайте =)

Понравилась статья? Поделить с друзьями:
  • Textbox excel vba 2010
  • Textbox controlsource vba excel
  • Textbox control in excel vba
  • Textbox backcolor in excel vba
  • Text of more than word