Quantcast
Channel: Word for Developers forum
Viewing all 4350 articles
Browse latest View live

OLE Automation Word 2013

$
0
0

We have implemented an Office solution for a large industrial customer in German engineering.<o:p></o:p>

In this solution oleAutomation is used to generate Word documents.<o:p></o:p>

 

With Word of Office 2010 this works fine.<o:p></o:p>

Unfortunately, after an update with Office 2013 we have big problems with the generation by Word oleAutomation. After our first tests, it seems that Word 2013 works much more asynchronously as older versions of Word. This causes that the documents are no longer correctly generated. Text blocks at the end come suddenly at the beginning, tables are corrupted etc.

Our question: is there a synchronization method or setting for Word OLE Automation, with which we can make sure that the OLE-macro statements run synchronously, i.e. carried out one after the other.<o:p></o:p>

Or is there here eventually another workaround.

We are migration the document generation completely with .net technology, but this needs a major redesign and the document generation must work correctly before this is done.

Thanks for any tip

Axel Biewer<o:p></o:p>


axel&ute


Create a table out of a nested list

$
0
0

I am trying to create a word table to represent a nested list.

'''**Pseudocode/Python/C#'''

the_list = [FT1,[ST1,[TT1, TT2, TT3], ST2,[TT1]], FT2,[ST1]]

iter_list(the_list)

def iter_list(the_list):
//Iterates through nested lists
   row_count = 0
   for each_item in the_list:
      column_count = 0
         if isinstance(the_list, list):
            column_count += 1
            iter_list(each_item)
         else:
            //Append item to table
            table.Rows(row_count+1).Cells(column_count+1).Range.Text = row[column_count] // Won't work
   row_count += 1


For example, if I have a list:


  • First Tier 1

       - Second Tier 1

            + Third Tier 1

            + Third Tier 2

            + Third Tier 3

       - Second Tier 2

            + Third Tier 1

            + Third Tier 2

  • First Tier 2

      - Second Tier 1

        

I would like to create a word table, like the one below:

[First Tier]   [Second Tier]    [Third Tier]

[First Tier 1]   [Second Tier 1]    [Third Tier 1]

                                                 -----------------

                                                  [Third Tier 2]

                                                 -------------------

                                                  [Third Tier 3]

                      -----------------------------------------

                     [Second Tier 2]      [Third Tier 1]

                                                  -------------------

                                                  [Third Tier 2]

--------------------------------------------------

[First Tier 2]  [Second Tier 1]
------------------------------------------------------------


** Just to clarify the table drawing, there are two rows in the first column, 3 rows in the second column, and 6 rows (including 1 blank) in the third/last column


Paste options not working in Word 2007

$
0
0

Hi,

I am not getting the "paste options" while pasting text form other  files. We have enabled "Show Paste option" from Word option but no Luck.

Please Assist.

Thanks

Nithin 


Nithin

Bookmarks or hyperlinks for navigating a long Word (2007) doc?

$
0
0

I have a word (2007) document with a table of contents and a body of text. I want to be able to jump to different sections of the doc from the table of contents. I am thinking hyperlnks. How do I set up my doc file so that when a user clicks on a table of contents item -- the doc will jump to that item page?


Rich P

Document Information Panel properties to show / hide text ranges in a Word document

$
0
0

I'm using a SharePoint content type that opens a Microsoft Word document with the New Document command.   The Document Information Panel (DIP) shows with its associated content type fields. I've deployed some of these properties as quick parts and they correctly change within the document where ever they are used.  Good stuff.

Now, I'd like to extend the functionality to selectively show/hide sections, tables, ranges of text based on whether certain checkboxes within the DIP are checked or not.  Is this possible? 

If it is I'm not sure of the best approach to follow here, whether macro driven or VSTO or other or not possible.

My current scenario is for the management of employment contracts and the associated clause inclusions/exclusions.  The bulk of the document's contents would be protected.  The aim is to simplify contract construction and to ensure errors are omitted by new contract authors.   The contract may need to be portable beyond the context of the SharePoint and corporate environment (ie when it is emailed to the recipient for instance) so it will need to maintain it's data integrity to ensure only selected text ranges remain visible.  Perhaps XPS/PDF becomes the final controlled version to ensure this.

mailmerge strange behavior saving documents

$
0
0

Hello,

since we changed from Windows XP to Windows 7 64 bit strange behavior occured in the following mailmerge:

step 1 runs the mailmerge to the printer

step 2 runs the mailmerge to save each document separately

step 3 check if all documents are saved

step 1 and 2 are at once, step 2 will run if step 3 says that not all the documents are saved.

We don't have any error for not saving to the server. In debug mode this cannot be reproduced.

The brand new pc (i5/4GB 4570) runs the code more slowly then the olders ones(i5/4GB 2500).

It takes several minutes to close winword (running in the background).

the following code is used:

PrivateSub PRINT(ByVal badge, ByVal CHOICE_LETTER,ByVal CHOICE)

       

       If Microsoft.VisualBasic.Left(CHOICE_LETTER, 1) ="T"Then

           CHOICE_LETTER = "U"& Microsoft.VisualBasic.Right(CHOICE_LETTER, 1)

       EndIf

       Dim reader1AsNewStreamReader("D:\template.txt")

       Dim templateAsString =Nothing

       template = reader1.ReadLine()

       reader1.Close()

        Dim owordAsObject

       oword = CreateObject("word.application")

       Dim odocAsObject

       odoc = oword.documents

       oword.documents.open(template)

       oword.visible = True

       Dim sourceAsString ="D:\"& CHOICE_LETTER &"_"& badge &".docx"

       oword.activedocument.mailmerge.opendatasource(source)

       

       If Microsoft.VisualBasic.Left(CHOICE_LETTER, 1) ="U"Then

           CHOICE_LETTER = "T"& Microsoft.VisualBasic.Right(CHOICE_LETTER, 1)

       EndIf

       Dim LANG_CHOICEAsString

       LANG_CHOICE = Microsoft.VisualBasic.Right(CHOICE, 1)

       Dim strSQLAsString

       strSQL = "SELECT * FROM Table where lang_id = '"& LANG_CHOICE& "'"

       oword.ActiveDocument.MailMerge.DataSource.QueryString = strSQL

       'Choice Print and save or only save

       Dim msgboxlabelAsString =""

       If badge ="001"Or badge ="004"Or badge ="005"Then

           msgboxlabel = "PRINT?"

       Else

           msgboxlabel = "Imprimer?"

       EndIf

       Dim result1AsDialogResult =MessageBox.Show(msgboxlabel, _

           "PRINTMENU", _

           MessageBoxButtons.YesNoCancel, _

           MessageBoxIcon.Question)

       If result1 = Windows.Forms.DialogResult.YesThen

           Dim printerAsString

           printer = ComboBox1.SelectedItem

           oword.activeprinter = printer

           oword.activedocument.mailmerge.destination = 1 'wdsendtoprinter

           With oword.Options

               .UpdateFieldsAtPrint = True

               .UpdateLinksAtPrint =True

           EndWith

           With oword.ActiveDocument.PageSetup

               .Orientation = 0 'wdOrientPortrait

           EndWith

 

           oword.activedocument.mailmerge.execute()

       EndIf

       

       Dim readerAsNewStreamReader("D:\number_"& LANG_CHOICE & ".txt")

       Dim count_linesAsString

       Count_lines = reader.ReadLine()

       reader.Close()

       Dim pathAsString 

       For xAsInteger = 1To count_lines

           With oword.ActiveDocument.MailMerge

               .destination = 0 'wdSendToNewDocument

               .MailAsAttachment = False

               .MailAddressFieldName = ""

               .MailSubject = ""

               .SuppressBlankLines = True

               With .DataSource

                   .FirstRecord = x

                   .LastRecord = x

               EndWith

               .DataSource.ActiveRecord = x

               path = oword.ActiveDocument.MailMerge.DataSource.DataFields("dosnumber").Value

               path = pathtoserver& path & "_"& CHOICE_LETTER &".doc"

               .Execute(pause:=True)

           EndWith

           If oword.ActiveDocument.Saved =FalseThen oword.ActiveDocument.saveas(path)

  

           oword.ActiveDocument.Close()

 

  

       Next

  

       odoc.close(0)

       oword.quit()

   EndSub

i added the following but it didn't resolve anything:

GC.Collect()

GC.WaitForPendingFinalizers()

GC.Collect()

GC.WaitForPendingFinalizers()

Any help is welcome.

Bert

Turn off Document Information Panel (DIP) when a document is created from a template saved in a document library

$
0
0

I want to immediately turn off the Document Information Panel (DIP) when I create a new document that is based on a template in a document library (no content type).

The following property is used to turn the Document Information Panel on or off:

Application.DisplayDocumentInformationPanel

Setting the property to false works fine when the DIP was being loaded but that seems not the case while the NewDocument event. What happens is, the DIP is displayed from the application again, after I had turned it off in the NewDocument event.

I did not find an appropriate event so I waited a second:

await Task.Factory.StartNew(() => System.Threading.Thread.Sleep(1000));

This works for me, or is there a better solution?



Is This the Best Forum For Writing Document-Level Add-Ins in VS 2010, 2012?

$
0
0
The title for my question says it all. Is this the best forum to which one should refer when creating Document-Level Add-Ins in VS 2010, 2012? Or is there another that might be better suited to the topic?

Tallisfan



Exporting documents as PDF and DOCX

$
0
0

Hi,

We have this document .docx and we want it to be exported as .pdf and .docx(but with another name) but, in adition, we want the original one to be continue as active and the exported files to be closed. The comments are in Portuguese, sorry, but we believe it won't be a problem.

Sub SalvarComo()
'
'   Esta macro salva o atual documento em sua pasta destino (decêndio de referência) com .docm e .pdf
'

Dim decendio
Dim mesnum
Dim mesred
Dim ano
Dim objExcel As Object
Dim objDoc As Object
Dim objComunicado As Object




' PRIMEIRO ELE ABRE O L:\Receita\Cronograma.xlsx E COLETA DECENDIO, MESNUM, MESRED E ANO
'
'   COM ESSES DADOS ELE NOMEARÁ O "SALVAR COMO" DO NOVO ARQUIVO



    Set objExcel = CreateObject("Excel.Application")
    Set objDoc = objExcel.Workbooks.Open("L:\COINT\GERED\__TC CONED\Receita\Cronograma.xlsx")
    objExcel.Visible = True

        decendio = objExcel.Workbooks("Cronograma.xlsx").worksheets("Plan1").Range("E1")
        mesnum = objExcel.Workbooks("Cronograma.xlsx").worksheets("Plan1").Range("G2")
        mesred = objExcel.Workbooks("Cronograma.xlsx").worksheets("Plan1").Range("F2")
        ano = objExcel.Workbooks("Cronograma.xlsx").worksheets("Plan1").Range("E3")
    
    objExcel.Workbooks("Cronograma.xlsx").Save
    objExcel.Workbooks("Cronograma.xlsx").Close
    

' COM ESTES DADOS, ELE SALVARÁ O NOVO ARQUIVO SEGUINDO O PADRÃO DE NOMENCLATURA
'   JÁ EXISTENTE TANTO EM .DOCM COMO EM .PDF


' SALVA COMO EM .DOCM NO NOVO LOCAL E FECHA O ARQUIVO
    ChangeFileOpenDirectory "L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\"
    ActiveDocument.SaveAs2 FileName:="L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\" & "Comunicado " _
               & ano & "_" & mesnum & " " & mesred & " " & decendio & "a Cota.docm", FileFormat:= _
        wdFormatXMLDocumentMacroEnabled, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
        
'    ActiveDocument.Close
        
' EXPORTA EM .PDF PARA O NOVO LOCAL
    ActiveDocument.ExportAsFixedFormat OutputFileName:="L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\" & "Comunicado " _
               & ano & "_" & mesnum & " " & mesred & " " & decendio & "a Cota.pdf", ExportFormat:= _
        wdWorkbookNormal, OpenAfterExport:=False, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
    ChangeFileOpenDirectory "L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\"

' EXPORTA EM .PDF PARA O NOVO LOCAL
    ActiveDocument.ExportAsFixedFormat OutputFileName:="L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\" & "Comunicado " _
               & ano & "_" & mesnum & " " & mesred & " " & decendio & "a Cota.pdf", ExportFormat:= _
        wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
    ChangeFileOpenDirectory "L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\"


' REABRE O DOCUMENTO MATRIZ
    
    Set objComunicado = Documents.Open("L:\COINT\GERED\__TC CONED\COMUNICADO\Comunicado_mdir - novo.docm")
'    Windows("L:\COINT\GERED\__TC CONED\COMUNICADO\Comunicado_mdir - novo.docm").Activate
    Documents("L:\COINT\GERED\__TC CONED\COMUNICADO\" & ano & "\" & mesnum & "\" & "Comunicado " & ano & "_" & mesnum & " " & mesred & " "& decendio & "a Cota.docm").Close

End Sub

Autoexecute query when printing

$
0
0

Hi

I've created a word document for adress labels where the data comes from the databank. Normally when you open the document a window prompts the user for execution of the query. I would like to have this query auto-executes when i print the document via interop.dll. Is this possible?

Extracting Tables AND Images from word Document

$
0
0

I know how to code VBA to simply loop through all Tables or loop through all inline shapes in a document separately but how would I go through a document and extract all Tables AND Images in order as they are presented in the document to copy into a separate document?

 

How to find and replace text in a table cell in word document

$
0
0

Hellow,

What I want to do: I need to find the text Orange, Grapes & Guava in column 2 and update the text in corresponding cell in column 3 for the same row as “Like”.  

Col 2

Col 3

Apple

Like

Orange

Dislike

Grapes

Dislike

Blue Berry

Dislike

Black Berry

Like

Guava

Dislike

Mange

Dislike

regards

SCOMDev


SCOMDev

Macro For Formating Pictures - add box frame, caption (Figure 1:)

$
0
0

I had a macro in 2003 to do the above and resize but we recently upgraded to office 2010.  I had previously recorded it, which I can't do with word 2010.  Very frustrating.  I have no experience with writing vba macro code and see there are multiple requests for similar type features, that people have kindly supplied.   I wonder if someone could provide the code for me to simply add a box (frame) around a picture that I would have previously selected, plus add a capture above the picture with Figure #:    I don't need it resized now with Word 2010.   I create documents that include a great number of pictures that I reference with the Figure #.  I normally select the pictures and then apply the macro but now I have to manually do this and its really time consuming. 

Apply VBA code to 1 table in Word document

$
0
0

Hello,

I found some code on a website (Greg Maxey) that inserts a new row into a table with all the controls of the previous row in it. I have a form in Word that contains multiple tables and was wondering if the code could be applied to the single table instead of being propogated through all of them. I'm not very familiar with vba - I do most of my coding in vb.net. I know they're similar to each other, but I usually end up having trouble going back and forth between the two.

Below is the code:

Option Explicit
Dim p_oTargetRow As Word.Row
Private Sub Document_ContentControlonEnter(ByVal ContentControl As ContentControl)
With Selection.Range
    If .Information(wdWithInTable) Then
        If .Cells(1).RowIndex = _
            .Tables(1).Range.Cells(.Tables(1).Range.Cells.Count).RowIndex Then
            If .Cells(1).ColumnIndex = _
            .Tables(1).Range.Cells(.Tables(1).Range.Cells.Count).ColumnIndex Then
                If MsgBox("This the last row/cell." & vbCrLf & _"Do you want to add a new row?", _
                          vbQuestion + vbYesNo) = vbYes Then
                    InsertRowWithContent
                End If
                Set p_oTargetRow = Selection.Rows(1)
            End If
        End If
    End If
End With
End Sub

Here is the code for the Module:

Option Explicit
Public p_oTargetRow As Word.Row
Sub InsertRowWithContent()
Dim vProtectionType As Variant
Dim oRows As Word.Row
Dim oRng As Word.Range
Dim iRow As Long
Dim lngIndex As Long
Dim strPassword As String
Dim strLocked As String
Dim arrLocked() As String
Dim oCC_Master As ContentControl
Dim oCC_Clone As ContentControl
    vProtectionType = ActiveDocument.ProtectionType
    On Error Resume Next
    Set oRows = p_oTargetRow
    If Error <> 0 Then
        If Selection.Information(wdWithInTable) Then
            Set oRows = Selection.Rows(1)
        End If
    End If

    If Not oRows Is Nothing Then
        Application.ScreenUpdating = False
            If vProtectionType <> wdNoProtection Then
                strPassword = "" 'Password can be inserted here if necessary
                ActiveDocument.Unprotect Password:=strPassword
            End If
            With Selection
                iRow = oRows.Index
                With .Tables(1)
                    If .Rows.Count > iRow Then
                        'Copy and paste content in new "inserted" row
                        iRow = iRow + 1
                        'Copy content
                        oRows.Range.Copy
                        'Because of a bug in Word - Content Controls
                        'in the following row must be unlocked.
                        For Each oCC_Master In .Rows(iRow).Range.ContentControls
                            strLocked = oCC_Master.LockContentControl & ","
                            oCC_Master.LockContentControl = False
                        Next oCC_Master
                        strLocked = Left(strLocked, Len(strLocked) - 1)
                        .Rows.Add .Rows(iRow)
                        Set oRng = .Rows(iRow).Range
                        oRng.MoveEnd wdCharacter, -1
                        oRng.Paste
                        arrLocked = Split(strLocked, ",")
                        For lngIndex = 1 To UBound(arrLocked)
                            .Rows(iRow).Range.ContentControls(lngIndex + 1).LockContentControl = _
                                    arrLocked(lngIndex)
                        Next lngIndex
                    Else
                        'Copy and paste row content in new appended row
                        .Rows.Last.Range.Copy
                        'Append the new row
                        .Rows.Add
                        Set oRng = .Rows.Last.Range
                        'Remove End of Row(EoR) mark
                        oRng.MoveEnd wdCharacter, -1
                        'Paste new content
                        oRng.Paste
                        iRow = iRow + 1
                    End If
                    'Work with new row content
                    With .Rows(iRow)
                        For lngIndex = 1 To .Previous.Range.ContentControls.Count
                            Set oCC_Master = .Previous.Range.ContentControls(lngIndex)
                            Set oCC_Clone = .Range.ContentControls(lngIndex)
                            With oCC_Clone
                                #If VBA7 Then
                                    If Int(Application.Version) >= 14 Then
                                        If .Type = wdContentControlCheckBox Then
                                            .Checked = False
                                        End If
                                    End If
                                #End If
                                If .Type = wdContentControlRichText Or _
                                    .Type = wdContentControlText Or _
                                    .Type = wdContentControlDate Then
                                        If Not .ShowingPlaceholderText Then
                                            .Range.Text = ""
                                        End If
                                End If
                                If .Type = wdContentControlPicture Then
                                    If Not .ShowingPlaceholderText Then
                                        If .Range.InlineShapes.Count > 0 Then
                                            .Range.InlineShapes(1).Delete
                                            .Range.InlineShapes(1).Width = _
                                                oCC_Master.Range.InlineShapes(1).Width
                                        End If
                                    End If
                                End If
                                If .Type = wdContentControlDate Then
                                    .Range.Text = ""
                                    .LockContentControl = oCC_Master.LockContentControl
                                End If
                            End With
                        Next lngIndex
                    End With
                End With
            End With
            If vProtectionType > -1 Then
                ActiveDocument.Protect Type:=vProtectionType, Password:=strPassword
            End If
            Application.ScreenUpdating = False
            Set p_oTargetRow = Nothing
        Else
            MsgBox "The cursor must be located in a table row containing content controls.", _
                    vbInformation + vbOKOnly, "INVALID SELECTION"
        End If
End Sub

Thanks to any and all who read this.
Also a link to the website where I got the code.


Join the darskide. We have cookies!


Wrong dmCopies member value when triyng to get print job info from DEVMODE after printintg from Word (2003,2007,2010)

$
0
0

We are developing program that monitors print jobs in the Windows system. Notification about print job are received by FindFirstPrinterChangeNotification and FindNextPrinterChangeNotification functions. With FindNextPrinterChangeNotification I'm getting DEVMODE structure (by JOB_NOTIFY_FIELD_DEVMODE parameter). I get wrong dmCopies member value when testing application with Microsoft Word. At first Word was returning only value "1". This is fixed by adding "ForceSetCopyCount" value in the registry (more information herehttp://support.microsoft.com/kb/919736/en-us). After that dmCopies started to show correct copy counts.

But this fix has one bug. I get incorrect results if I print documents in same Word (do not turn off Word application):

In first print job i print 1 copy, second time 2 copies, third time again 1 copy.

In my application i get this info from DEVMODE:

first job copy count = 1, second job copy count = 2, third job copie count = 2.  So, I get last max copie count if I try to set copy to 1.

This applies only for Microsoft Word. Excel, PowerPoint works OK. 

After closing and opening Word application I get correct copy count value for first document. So it seems that Word forgets to reset copy count for 1. This bug appears only if I set copy count from higher to 1, but if I set it from 5 to 3 I'm getting 5 and 3 in dmCopies.

Anyone encountered this problem before?

 

 





How do I create a new word document and add a block of text stored in a variable to it in C#?

$
0
0

Hi,

I have some code that has a range of text stored in a variable called originalText. How do I create a new document and put the contents of originalText in it? Also, the text inside orginalText keeps changing based on a set of if conditions that I have so I want a new document to be created every time a new if condition appears.

Many thanks in advance!

invisible image in header section

$
0
0

Hallo,

i have a word 2010 template with invisible Images in the Header section and i can't make them visible to delete them.

Inside the XML-structure of the template are 2 images files in the word/media folder. These files are referenced in the file word/header2.xml.

How can i make them visible in word, and how can i access these images in vba.  I've tried shapes and inlineshapes collections, but they're empty.

C#, word addin, programmary put tabulators to document

$
0
0
Hi,

I try to create addin to word application.

How i can put programmary put some tabulators to document?
Like on the screen: https://dl.dropboxusercontent.com/u/11254269/screen_word.jpg 
(Tab stop 16cm, Alignment: Right, Leader 3)

Regards,
Daro

c#, word addin, programmary disable autosave/autorecover.

$
0
0

Hello,

I making word addin in c# (visual studio 2013).

How i can programmary disable autosave and autorecovery in word addin?

Please give me example for an application-level add-in.

Regards,

Daro

c#, word addin, copy content control

$
0
0
Hiho,

I try to create word addin.

I put some content control in word document.

If i try to copy&put content_control, how can capture id of new content_control?

Entering,Exiting event on content_control, dont work with copying content:(

Please help

Regards,
Daro
Viewing all 4350 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>