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
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.
04-02-2016, 04:16 AM |
|||
|
|||
Insert and Filling Textbox using VBA
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 |
04-02-2016, 04:58 AM |
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
__________________ |
04-02-2016, 05:11 AM |
|||
|
|||
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 |
04-02-2016, 05:48 AM |
|||
|
|||
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. PS Thanks Graham for the tip on running already open word application will try it out!! |
04-02-2016, 06:14 AM |
|||
|
|||
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 |
04-02-2016, 02:35 PM |
|||
|
|||
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. |
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
44.3k7 gold badges65 silver badges115 bronze badges
asked Jun 15, 2013 at 18:12
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 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 | ||
|
для закрытия документа без сохранения:
Visual Basic | ||
|
у меня код макроса получился такой: принтер «Universal Document Converter» не установлен по умолчанию!
Visual Basic | ||
|
Ну вроде все =) если что спрашивайте =)