Note: The other languages of the website are Google-translated. Back to English
Log in  \/ 
x
or
x
Inscreva-se  \/ 
x

or

Como preservar as linhas de grade ao preencher a cor no Excel?

Como todos sabemos, quando preenchemos a cor de fundo para as células, as linhas de grade também serão cobertas, neste caso, como poderíamos manter as linhas de grade enquanto preenchemos a cor de fundo nas células do Excel para obter a seguinte captura de tela mostrada.

doc manter linhas de grade preencher cor 1

Preserve as linhas de grade enquanto preenche a cor com o código VBA


seta azul bolha direita Preserve as linhas de grade enquanto preenche a cor com o código VBA


Normalmente, não há uma maneira direta de resolvermos esse trabalho, mas, aqui, posso apresentar um código VBA para você. Faça o seguinte:

1. Segure o ALT + F11 chaves para abrir o Microsoft Visual Basic para Aplicações janela.

2. No lado esquerdo Projeto-VBAProject painel, clique duas vezes ThisWorkbook sob o expandido VBAProject, copie e cole o seguinte código VBA no módulo em branco:

Código VBA: preserva as linhas de grade enquanto preenche a cor

Dim xRgPre As Range
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    On Error Resume Next
    If Not xRgPre Is Nothing Then DrawBorders xRgPre
    Set xRgPre = Target
End Sub
Private Sub DrawBorders(ByVal Rg As Range)
'Updateby Extendoffice 20160725
    Dim xCell As Range
    Application.ScreenUpdating = False
    For Each xCell In Rg
        If xCell.Interior.ColorIndex = xlNone Then
            With xCell.Borders
                If .ColorIndex = 15 Then
                    .LineStyle = xlNone
                End If
            End With
        Else
            With xCell.Borders
                If .LineStyle = xlNone Then
                    .Weight = xlThin
                    .ColorIndex = 15
                End If
            End With
        End If
    Next
    Application.ScreenUpdating = True
End Sub

doc manter linhas de grade preencher cor 2

3. E então salve e feche a janela de código, agora, ao preencher uma cor para um intervalo de células, as linhas de grade serão mostradas automaticamente.


As melhores ferramentas de produtividade para escritório

O Kutools for Excel resolve a maioria dos seus problemas e aumenta sua produtividade em 80%

  • armadilha para peixes: Insira rapidamente fórmulas complexas, gráficos e qualquer coisa que você tenha usado antes; Criptografar células com senha; Criar lista de discussão e enviar emails ...
  • Super Formula Bar (edite facilmente várias linhas de texto e fórmula); Layout de leitura (ler e editar facilmente um grande número de células); Colar na faixa filtrada...
  • Mesclar células / linhas / colunas sem perder dados; Dividir o conteúdo das células; Combinar linhas / colunas duplicadas... Evite células duplicadas; Comparar intervalos...
  • Selecione Duplicado ou Único Linhas; Selecione linhas em branco (todas as células estão vazias); Super Find e Fuzzy Find em muitos livros; Seleção aleatória ...
  • Cópia exata Várias células sem alterar a referência da fórmula; Criação automática de referências para várias folhas; Inserir marcadores, Caixas de seleção e mais ...
  • Extrair Texto, Adicionar texto, remover por posição, Remover Espaço; Criar e imprimir subtotais de paginação; Converter entre conteúdo de células e comentários...
  • Super Filtro (salvar e aplicar esquemas de filtro a outras planilhas); Classificação Avançada por mês / semana / dia, frequência e mais; Filtro Especial por negrito, itálico ...
  • Combine pastas de trabalho e planilhas; Mesclar tabelas com base em colunas-chave; Divida os dados em várias folhas; Conversão em lote de xls, xlsx e PDF...
  • Mais de 300 recursos poderosos. Suporta Office / Excel 2007-2019 e 365. Suporta todos os idiomas. Fácil implantação em sua empresa ou organização. Teste gratuito de 30 dias com recursos completos. Garantia de devolução do dinheiro em 60 dias.
guia kte 201905

Guia do Office traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
officetab bottom
Say something here...
symbols left.
You are guest
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    sculbertson1106 · 27 days ago
    This works great. (Thanks)  But here's the real question - Why does Excel allow gridlines to disappear when filling cells with color in the first place? Just another dumb glitch in the techy world that so-called intelligent developers never think of. I mean, the gridlines, by default are supposed to be there anyway...so....
  • To post as a guest, your comment is unpublished.
    Chad · 1 years ago
    Thank you! I was pulling hairs trying to get the nice grey-ish borders to stay after colorizing. Can't believe Microsoft hasn't already implemented this.
  • To post as a guest, your comment is unpublished.
    Alissa · 2 years ago
    Another fix, if you don't want to mess with code:
    First figure out which color gray matches the default lines and have it in mind.
    In the Home tab click Cell styles, right click on Normal, click Modify -> Format -> Border. For Line Color, select that gray. For Presets, select Outline. Done.
    Now you may have to select all (CTRL+A / Command+A) and click Cell styles -> Normal to make sure it's applied to all cells. When you fill a cell, the borders will remain.
    • To post as a guest, your comment is unpublished.
      JL · 7 months ago
      This helped me SO much. I have literally been searching so many places and this is the only explanation that worked! Thank you!!!
    • To post as a guest, your comment is unpublished.
      Fox · 1 years ago
      Alissa , I had the same problem couldn`t get it fixed but your reply helped me a lot , so thank you very much , you are genius .
    • To post as a guest, your comment is unpublished.
      Armaan Sandhu · 1 years ago
      Thank you!!
  • To post as a guest, your comment is unpublished.
    Andrew · 3 years ago
    Cool, but now if I fill some cells, and hit Ctrl+Z to undo, it won't work. Will not undo.
    • To post as a guest, your comment is unpublished.
      skyyang · 3 years ago
      Hello, Andrew,
      Yes, the above code can not support Undo feature, you should fill no color manually to undo your work.
      Thank you!
  • To post as a guest, your comment is unpublished.
    barbatus · 3 years ago
    use only standard colors ;)
  • To post as a guest, your comment is unpublished.
    Terry · 3 years ago
    works but one has to correct the error if you see it.
    Dim xRgPre As Range
    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    On Error Resume Next
    If Not xRgPre Is Nothing Then DrawBorders xRgPre
    Set xRgPre = Target


    *************************************
    Should READ... as the If statement only ensures that something is there to set to memory allocation.

    One could set the next line below for clean up and not allow memory leaks.

    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    On Error Resume Next
    Set xRgPre = Target
    If Not xRgPre Is Nothing Then DrawBorders xRgPre
    'For ensured memory leaks do not happen
    'Clean up the memory allocated after it is not needed.
    Set xRqPre = Nothing



    Have a nice day..
    • To post as a guest, your comment is unpublished.
      James Godesky · 1 years ago
      Does not work with Conditional Formatting. Set xRqPre = Nothing gives error: variable not defined (deleted the line).Screen jiggles here too, using 2010. Other wise its a cool tool..
  • To post as a guest, your comment is unpublished.
    Vic · 3 years ago
    Works fine, but sadly every time I now click on a cell, the worksheet judders! Removed the VBA and the judder has ceased. Wonder why this should happen?
    • To post as a guest, your comment is unpublished.
      jdjshark@gmail.com · 2 years ago
      Same here with Excel 2016. I'm getting freezing and mostly blanked out screen for several seconds, especially when selecting many cells. It's a shame because it does work perfectly otherwise.
    • To post as a guest, your comment is unpublished.
      skyyang · 3 years ago
      Hi, Vic,
      There is no this problem in my Excel workbook, which Excel version do you use?
  • To post as a guest, your comment is unpublished.
    dolphinks · 3 years ago
    Fabulous fix!!