i am using vb.net and I have a word document that I am editing.
I want to remove the page break only from page 6 (for example ) to the end of the document and not from the entire document.
The code I have is for the entire document - How should I change it?
Dim paragraphs As Word.Paragraphs
paragraphs = doc.Paragraphs
For Each paragraph As Word.Paragraph In paragraphs
If paragraph.Range.Text.Trim() = String.Empty Then
paragraph.Range.[Select]()
wordapp.Selection.Delete()
End If
Next
This works for me. This will delete the pagebreak (if exists) from the 6th Page.
Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
'~~> Define your Excel Objects
Dim wrdApp As New Word.Application
Dim wrdDoc As Word.Document
'~~> Page NO
Dim pgNo As Integer = 6
Dim i As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
wrdDoc = wrdApp.Documents.Open("C:\Users\Siddharth\Desktop\Document1.docx")
'~~> Display Word
wrdApp.Visible = True
With wrdDoc
For i = .Paragraphs.Count To 1 Step -1
If Asc(.Paragraphs(i).Range.Text) = 12 And _
.Paragraphs(i).Range.Information(Word.WdInformation.wdActiveEndPageNumber) = pgNo Then
.Paragraphs(i).Range.Delete()
Exit For
End If
Next i
End With
End Sub
End Class
Related
I was on MS Word 2007 where the macros worked fine.
After upgrading to MS Word 2016 the method Document_ContentControlOnExit does not fire.
Since I write very few MS Word macros I don’t keep up on fundamental change to the architecture. Has something changed in MS Word 2016 that would cause the code to stop working?
The set of methods will detect a Content Control exit. Then update all Content Controls with the same tag name with the new value.
I have put a breakpoint in Document_ContentControlOnExit. Then made some changes to a Content Control. Nothing.
Sub SetUp()
Set eventHandler.doc = ActiveDocument
End Sub
Sub Document_Close()
Call UpdateAllFields
End Sub
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
ccTag = ContentControl.Tag
ccValue = ContentControl.Range.Text
Call updateValueInAllInstances(ccTag, ccValue)
End Sub
Sub updateValueInAllInstances(ccTag, ccValue)
Dim doc As Document
Dim ccs As ContentControls
Dim cc As ContentControl
Set doc = ActiveDocument
For Each cc In doc.SelectContentControlsByTag(ccTag)
' If the author of the document did not lock the contents, then perform a auto update.
If cc.LockContents Then
Respose = MsgBox("The author of this cookbook has deliberately designed this specific content control to not be editable.", 0, "Content Control is not editable", "", 1000)
Else
cc.Range.Text = ccValue
End If
Next cc
End Sub
Sub UpdateAllFields()
Dim objStory As Range
Dim objTOC As TableOfContents
Dim objTOA As TableOfAuthorities
Dim objTOF As TableOfFigures
Dim objIndex As Index
Application.ScreenUpdating = False
Application.DisplayAlerts = wdAlertsNone
For Each objStory In ActiveDocument.StoryRanges
UpdateFieldsInStory objStory
While Not (objStory.NextStoryRange Is Nothing)
Set objStory = objStory.NextStoryRange
UpdateFieldsInStory objStory
Wend
Next
For Each objTOC In ActiveDocument.TablesOfContents
objTOC.Update
Next
For Each objTOA In ActiveDocument.TablesOfAuthorities
objTOA.Update
Next
For Each objTOF In ActiveDocument.TablesOfFigures
objTOF.Update
Next
For Each objIndex In ActiveDocument.Indexes
objIndex.Update
Next
Application.DisplayAlerts = wdAlertsAll
Application.ScreenUpdating = True
End Sub
Private Sub UpdateFieldsInStory(iobjStory As Range)
Dim objShape As Shape
With iobjStory
.Fields.Update
Select Case .StoryType
Case wdMainTextStory, wdPrimaryHeaderStory, _
wdPrimaryFooterStory, wdEvenPagesHeaderStory, _
wdEvenPagesFooterStory, wdFirstPageHeaderStory, _
wdFirstPageFooterStory
For Each objShape In .ShapeRange
With objShape.TextFrame
If .HasText Then .TextRange.Fields.Update
End With
Next
End Select
End With
End Sub
I was hoping the code was not so out of date that it would keep working.
This mistake was what Cindy Meister pointed out. When I copied the macro code from the old to the new template I failed to notice the location in the Visual Basic Editor. Once the code was in the correct place it worked.
I have an ActiveX Command Button that when pressed opens a userform to allow data entry into the word document. This button needs to remain visible when working on the document but not visible when printing.
How can I hide/make invisible only when printing?
Unlike in Excel VBA where the properties include an option to 'PrintObject', word VBA does not have this functionality. The best I have been able to do is delete the button after being clicked but this is not really what I want.
'Needs to hide button only on printing, not delete it
UserForm2.Show
CommandButton1.Select
Selection.Delete
I assume you are having ActiveX Command Button in word and using user form entered data gets feed in corresponding fields and you are closing user form and then trying to print document and printed file should not have ActiveX Command Button in it
Paste the following code into CommandButton_Click event
Private Sub CommandButton1_Click()
With ActiveDocument
.Shapes(1).Visible = msoFalse
.PrintOut Background:=False
.Shapes(1).Visible = msoTrue
End With
End Sub
#ille P. - You should post a new question, perhaps with a link to this one.
Try the Shapes collection as well as inlineshape collection.
The following is suggested by Ibby on the Microsoft Word MVP VBA FAQ pages:
Private Sub CommandButton1_Click()
With ActiveDocument
.Shapes(1).Visible = msoFalse
.PrintOut Background:=False
.Shapes(1).Visible = msoTrue
End With
End Sub
So translating to the collection:
Dim oShape as Shape
For Each oShape in ActiveDocument.Shapes
oShape.Visible = False
Next oShape
That would, though hide all shapes, not just your buttons.
You could add bookmarks to your buttons and use them as a filtering Range.
After investigating what happens with the CommandButtons, I detected that in the document they are included (if it has not been edited to be a Shape) in the InLineShape collection by being encapsulated in an InLineShape object.
It would be great if we could directly typecast from CommandButton to InShapeLine but I think Microsoft doesn't allow it, too bad.
The idea is to create two class modules:
One will be an event manager to capture the 'before printing' event and another.
The other will be an encapsulation of an InLineShape object that will have the methods to make the object visible, taking advantage of the Brightness property of the PictureFormat object.
CLASS clsButton
Option Explicit
Private M_ishpButton As InlineShape
Public Property Get button() As InlineShape
Set button = M_ishpButton
End Property
Public Property Set button(oObj As InlineShape)
Set M_ishpButton = oObj
End Property
Public Property Get Visible() As Boolean
Visible = Not bIsHidden
End Property
Public Property Let Visible(bValue As Boolean)
Dim oPictureFormat As PictureFormat
Set oPictureFormat = M_ishpButton.PictureFormat
If bValue Then
Call show
Else
Call hide
End If
End Property
Private Function bIsHidden() As Boolean
Dim oPictureFormat As PictureFormat
Set oPictureFormat = M_ishpButton.PictureFormat
If oPictureFormat.Brightness = 1 Then bIsHidden = True: Exit Function
bIsHidden = False
End Function
Private Sub hide()
Dim oPictureFormat As PictureFormat
Set oPictureFormat = M_ishpButton.PictureFormat
oPictureFormat.Brightness = 1
End Sub
Private Sub show()
Dim oPictureFormat As PictureFormat
Set oPictureFormat = M_ishpButton.PictureFormat
With oPictureFormat
.Brightness = 0.5
.Contrast = 0.5
End With
End Sub
CLASS clsEvents
Option Explicit
Public WithEvents appWord As Word.Application
Public WithEvents docWord As Word.Document
Private m_button As New clsButton
Private Sub appWord_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
'If process is not cancel and button is not visible
With m_button
If Cancel = False And .Visible = True Then
.Visible = False
End If
End With
End Sub
Private Sub appWord_WindowDeactivate(ByVal Doc As Document, ByVal Wn As Window)
'If button is not visible then set to true
With m_button
If .Visible = False Then
.Visible = True
End If
End With
End Sub
Public Property Set button(oObj As clsButton)
Set m_button = oObj
End Property
CLASS ThisDocument
Now, in ThisDocument class should create objects and linking
Dim oEventsManager As New clsEvents
Dim oEditedButton As New clsButton
Const BUTTON_LINKS As String = "cmdUpdateLinks" 'For example
Dim oInShpDoc As Word.InlineShape, oOleDoc As Word.OLEFormat, oInShapesDoc As Word.InlineShapes
Public Sub Set_Manager_Events()
Set oEventsManager.appWord = Word.Application 'ThisDocument.Application
Set oEventsManager.docWord = ThisDocument
Set oInShpDoc = FNC_oGet_Button_Variable(BUTTON_LINKS)
If Not oInShpDoc Is Nothing Then
Set oEditedButton.button = oInShpDoc
Set oEventsManager.button = oEditedButton
End If
End Sub
'###### EVENTOS OF BUTTON
Private Sub cmdUpdateLinks_Click()
If oEventsManager.appWord Is Nothing Then Call Set_Manager_Events
Call UpdateLinks ' Is one example
End Sub
Public Function FNC_oGet_Button_Variable(sCodeName As String) As InlineShape
Dim oForm As InlineShape, oFormsInLine As InlineShapes, oOLEFormat As OLEFormat
Set oFormsInLine = ThisDocument.InlineShapes
If oFormsInLine .Count < 1 Then GoTo bye
i = 0
For Each oForm In oFormsInLine
With oForm
Set oOLEFormat = .OLEFormat
If Not oOLEFormat Is Nothing Then
If InStr(1, oOLEFormat.ClassType, "CommandButton") > 0 Then
If .OLEFormat.Object.Name = sCodeName Then
Set FNC_oGet_Button_Variable= oForm
Exit Function
End If
End If
End If
End With
Next
bye:
Set FNC_oGet_Button_Variable = Nothing
End Function
With this you will can hide button for printing.
I want to add dynamically CommandButtons to my Userform within the For-Loop. How can i get add new CommandButtons in the For-Loop?
Dim CommandButtons(5) As clsCommandButtons
Private Sub UserForm_Initialize()
Dim zaehler As Integer
For zaehler = 0 To 4
Set CommandButtons(zaehler) = New clsCommandButtons
Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler)
Next
End Sub
And This is my class:
Option Explicit
Public WithEvents cmdCommandButton As CommandButton
Private Sub cmdCommandButton_Click()
Dim sFilepath As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.InitialFileName = ActiveWorkbook.Path & "\"
.Filters.Add "TextFiles", "*.txt", 1
.FilterIndex = 1
If .Show = -1 Then
sFilepath = .SelectedItems(1)
End If
End With
Cells(c_intRowFilterPathStart, c_intClmnFilterPath) = sFilepath
End Sub
I don't know how to handle this Error. How can i fix this?
I assume you get the error because you're accessing a control that doesn't exist. Note that the controls are counted from 0 to Me.Controls.count-1, so probably your issue is solved with
Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler-1)
But I guess a better solution is to name your buttons and assign them by name:
Set CommandButtons(zaehler).cmdCommandButton = Me.Controls("CommandButton" & zaehler)
Define the CommandButtons collection as a Variant:
Dim CommandButtons(15) As Variant, instead of Dim CommandButtons(15) As clsCommandButtons.
In this Variant, you would put your CommandButtons. This is some minimal code, that would help you get the basics of what I mean:
CustomClass:
Private Sub Class_Initialize()
Debug.Print "I am initialized!"
End Sub
In a module:
Private SomeCollection(4) As Variant
Public Sub TestMe()
Dim cnt As Long
For cnt = 1 To 4
Set SomeCollection(cnt) = New CustomClass
Next cnt
End Sub
From this small running code, you can start debugging further :)
I think your problem is in the Me.Controls(zaehler) part. zaehler starts at 1, but Me.Controls(...) starts at 0.
Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler - 1)
would probably solve it
Dim a() As clsCommandButton
Private Sub UserForm_Initialize()
Dim c As Control
On Error GoTo eHandle
For Each c In Me.Controls
If TypeName(c) = "CommandButton" Then
ReDim Preserve a(UBound(a) + 1)
Set a(UBound(a)) = New clsCommandButton
Set a(UBound(a)).cmd = c
End If
Next c
Exit Sub
eHandle:
If Err.Number = 9 Then
ReDim a(0)
End If
Resume Next
End Sub
With a class as follows
Public WithEvents cmd As commandbutton
Private Sub cmd_Click()
MsgBox "test"
End Sub
I am trying to list all the opened workbooks and their corresponding sheets in the task bar after that I should be able to select one workbook of the list and open it. My first try was to to show Excel process in Task-Manager but it only shows one open workbook without detecting the number of sheets.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim name As Process() = Process.GetProcessesByName("Excel")
For Each names In name
ListView1.Items.Add(names.MainWindowTitle)
If names.MainWindowTitle <> "" Then
ListBox1.Items.Add(names.MainWindowTitle)
End If
Next
End Sub
Next I tried to use this code but also I can only display one opened workbook, I don't know how to loop through them. I don't have problem of changing the whole code if you have any other method cause I am not sure that it's the solution.
Dim oXL As Microsoft.Office.Interop.Excel.Application
oXL = TryCast(System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
oXL.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMinimized
Dim y As String
y = oXL.ActiveWorkbook.Name
ListBox1.Items.Add(y)
Dim objExcel As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Dim objWorkBook As Excel.Workbook = Nothing
Dim totalWorkBooks As Integer = objExcel.Workbooks.Count
For i As Integer = 1 To totalWorkBooks
objWorkBook = objExcel.Workbooks(i)
With objWorkBook
FullName = .FullName
OnlyName = .Name
I came up with this site: http://forums.codeguru.com/showthread.php?15568-WRITING-DATA-TO-WORD-DOCUMENT-FROM-VB
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Dim wd As Word.Application
Dim wdDoc As Word.Document
wd = New Word.Application
wd.Visible = True
wdDoc = wd.Documents.Add("D:\Employees.dotx") 'Add document to Word
With wdDoc
.FormFields("E_Name").Result = txtLastName.Text [error]
.FormFields("E_NName").Result = txtFirstName.Text
.FormFields("E_Address").Result = txtMiddleName.Text
End With
wdDoc.PrintPreview() 'Opens print Preview Window
wdDoc.SaveAs("D:\doc1.DOC") 'Saves the Document
wd.Application.Quit() 'Closing Word Application
wd = Nothing 'Releasing References to Variable
End Sub
Error: The requested member of the collection does not exist.
Can anyone help me with connecting microsoft word with VB.net
The video you are referring is using vb6. In VS 2010, you can do it like this:
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Static wd1 As Word.Application
Static wd1Doc As Word.Document
wd1 = New Word.Application
wd1.Visible = True
wd1Doc = wd1.Documents.Add("yourFilePath\profile.dot") 'example: "D:\profile.dot"
With wd1Doc
.FormFields("W_Lname").Result = txtLastName.Text 'In VS2010, property `Range` is Readonly.
.FormFields("W_Fname").Result = txtFirstName.Text 'You need to use `Result`
.FormFields("W_Mname").Result = txtMiddleName.Text
End With
wd1 = Nothing
wd1Doc = Nothing
End Sub
But first, you need to add Microsoft Word <ver> Object Library to your reference.
And if you still see the errors, you might need to import:
Imports Microsoft.Office.Interop
Note: If you are using MS Office 2013, your file extension should be .dotx (profile.dotx)
So you might need to change
wd1Doc = wd1.Documents.Add("yourFilePath\profile.dotx")
^
Try to browse this link and read carefully all the topics http://wiki.smartsimple.com/wiki/Adding_Form_Fields_to_a_MS_Word_Document
Dim wd As Word.Application
Dim wdDoc As Word.Document
wd = New Word.Application
wd.Visible = True
wdDoc = wd.Documents.Add("D:\Employees\Employees.dotx") 'Add document to Word
With wdDoc
.FormFields("E_Name").Result = txtLastName.Text
.FormFields("E_Nickname").Result = txtNickname.Text
.FormFields("E_Address").Result = txtAddress.Text
.FormFields("E_Position").Result = cboPosition.Text
End With
wdDoc.SaveAs("D:\Employees\" & txtLastName.Text & "" & txtFirstName.Text & ".DOC") 'Saves the Document
MsgBox("Please check the folder of employees and open the name of the employee to print his/her document", MsgBoxStyle.OkOnly)
wd.Application.Quit() 'Closing Word Application
wd = Nothing 'Releasing References to Variable
wdDoc = Nothing
That will do the trick, no errors..
Note:Please create a destination folder for your documents like this one
"D:\Employees\Employees.dotx", this line of codes instantly save the word document in the destination folder for later printing purposes. Cheers