Compartilhar via


Como: Formatar texto em documentos

Se aplica a

As informações contidas neste tópico se aplicam apenas às especificado Ferramentas do Visual Studio para o Office projetos e as versões do Microsoft Office.

Tipo de Projeto

  • Projetos de nível de documento

  • Projetos de nível de aplicativo

Versão do Microsoft Office

  • Word 2003

  • Word 2007

For more information, see Recursos disponíveis pelo aplicativo e o tipo de projeto.

Você pode usar o objeto Range para formatar texto em um documento do Microsoft Office Word.

O exemplo a seguir seleciona o primeiro parágrafo do documento e altera o tamanho da fonte, o nome da fonte e o alinhamento.Ele, Avançar, seleciona o intervalo e exibe uma caixa de mensagem para fazer uma Pausar antes de executar a Avançar seção do código.A Avançar seção chama o método Undo de item de host Microsoft.Office.Tools.Word.Document (para uma personalização de nível de documento) ou a classe de Microsoft.Office.Interop.Word.Document (para um aplicativo-nível Adicionar - in) três vezes.Ele aplica o estilo de Recuar normal e exibe uma caixa de mensagem para pausar o código.Em seguida, o código chama o método de Undo uma vez e exibe uma caixa de mensagem.

Observação:

Você irá notar que você Gravar menos código formatação se você Definir estilos para Tudo as suas necessidades formatação.Além disso, estilos são mais fáceis de manter.Se você precisar alterar a formatação de um documento, você só precisa fazê-lo em um local (o estilo), portanto, você não precisará pesquisar e substituir por meio de seu código.

Exemplo de personalização de nível de documento

Para formatar texto usando uma personalização de nível de documento

  • O exemplo a seguir pode ser usado em uma personalização de nível de documento.Para usar esse código, execute-de a classe ThisDocument no seu projeto.

    Private Sub RangeFormat()
    
        ' Set the Range to the first paragraph.
        Dim rng As Word.Range = Me.Paragraphs(1).Range
    
        ' Change the formatting.
        rng.Font.Size = 14
        rng.Font.Name = "Arial"
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
    
        rng.Select()
        MessageBox.Show("Formatted Range")
    
        ' Undo the three previous actions.
        Me.Undo(Times:=3)
    
        rng.Select()
        MessageBox.Show("Undo 3 actions")
    
        ' Apply the Normal Indent style.
        rng.Style = "Normal Indent"
    
        rng.Select()
        MessageBox.Show("Normal Indent style applied")
    
        ' Undo a single action.
        Me.Undo()
    
        rng.Select()
        MessageBox.Show("Undo 1 action")
    End Sub
    
    private void RangeFormat() 
    { 
        // Set the Range to the first paragraph. 
        Word.Range rng = this.Paragraphs[1].Range; 
    
        // Change the formatting. 
        rng.Font.Size = 14; 
        rng.Font.Name = "Arial"; 
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
        rng.Select(); 
        MessageBox.Show("Formatted Range"); 
    
        // Undo the three previous actions. 
        object numTimes3 = 3; 
        this.Undo(ref numTimes3); 
    
        rng.Select(); 
        MessageBox.Show("Undo 3 actions"); 
    
        // Apply the Normal Indent style. 
        object indentStyle = "Normal Indent"; 
        rng.set_Style(ref indentStyle); 
    
        rng.Select(); 
        MessageBox.Show("Normal Indent style applied"); 
    
        // Undo a single action. 
        object numTimes1 = 1; 
        this.Undo(ref numTimes1); 
    
        rng.Select(); 
        MessageBox.Show("Undo 1 action"); 
    }
    

Nível de aplicativo Adicionar - exemplo

Ao formatar texto usando um aplicativo-nível Adicionar - in

  • O exemplo a seguir pode ser usado em um nível de aplicativo Adicionar - in.Este exemplo usa o documento ativo.Para usar esse código, execute-de a classe ThisAddIn no seu projeto.

    Private Sub RangeFormat()
    
        ' Set the Range to the first paragraph.
        Dim document As Word.Document = Me.Application.ActiveDocument
        Dim rng As Word.Range = document.Paragraphs(1).Range
    
        ' Change the formatting.
        rng.Font.Size = 14
        rng.Font.Name = "Arial"
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
    
        rng.Select()
        MessageBox.Show("Formatted Range")
    
        ' Undo the three previous actions.
        document.Undo(Times:=3)
    
        rng.Select()
        MessageBox.Show("Undo 3 actions")
    
        ' Apply the Normal Indent style.
        rng.Style = "Normal Indent"
    
        rng.Select()
        MessageBox.Show("Normal Indent style applied")
    
        ' Undo a single action.
        document.Undo()
    
        rng.Select()
        MessageBox.Show("Undo 1 action")
    End Sub
    
    private void RangeFormat()
    {
        // Set the Range to the first paragraph. 
        Word.Document document = this.Application.ActiveDocument;
        Word.Range rng = document.Paragraphs[1].Range;
    
        // Change the formatting. 
        rng.Font.Size = 14;
        rng.Font.Name = "Arial";
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
        rng.Select();
        MessageBox.Show("Formatted Range");
    
        // Undo the three previous actions. 
        object numTimes3 = 3;
        document.Undo(ref numTimes3);
    
        rng.Select();
        MessageBox.Show("Undo 3 actions");
    
        // Apply the Normal Indent style. 
        object indentStyle = "Normal Indent";
        rng.set_Style(ref indentStyle);
    
        rng.Select();
        MessageBox.Show("Normal Indent style applied");
    
        // Undo a single action. 
        object numTimes1 = 1;
        document.Undo(ref numTimes1);
    
        rng.Select();
        MessageBox.Show("Undo 1 action");
    }
    

Consulte também

Tarefas

Como: Definir e selecionar intervalos em documentos

Como: Inserir texto em documentos do Word

Como: Pesquisar para texto em documentos