Como automatizar o Excel a partir do Visual Basic .NET para preencher ou obter dados num intervalo utilizando matrizes

Resumo

Este artigo demonstra como automatizar o Microsoft Excel e como preencher um intervalo de várias células com uma matriz de valores. Este artigo também demonstra como obter um intervalo de várias células como uma matriz através da Automatização.

Mais Informações

Para preencher um intervalo de várias células sem preencher uma célula uma de cada vez, pode definir a propriedade Valor de um objeto Intervalo para uma matriz tridimensional. Da mesma forma, uma matriz de valores em duas dimensões pode ser recuperada para múltiplas células ao mesmo tempo ao utilizar a propriedade Valor. Os passos seguintes demonstram este processo para definir e recuperar dados através de matrizes tridimensionais.

Criar o Cliente de Automatização para o Microsoft Excel

  1. Inicie o Microsoft Visual Studio .NET.

  2. No menu Ficheiro, clique em Novo e, em seguida, clique em Projeto. Selecione Aplicação do Windows a partir dos tipos de Projeto do Visual Basic. Por predefinição, é criado o Formulário1.

  3. Adicione uma referência à Biblioteca de Objetos do Microsoft Excel. Para tal, siga estes passos:

    1. No menu Projeto, clique em Adicionar Referência.
    2. No separador COM, localize Biblioteca de Objetos do Microsoft Excel e, em seguida, clique em Selecionar.

    Nota O Microsoft Office 2007 e o Microsoft Office 2003 incluem As Assemblagens Interop Principais (PIAs). O Microsoft Office XP não inclui PIAs, mas estes podem ser transferidos.

  4. Clique em OK na caixa de diálogo Adicionar Referências para aceitar as suas seleções. Se lhe for pedido para gerar embrulhos para as bibliotecas que selecionou, clique em Sim.

  5. No menu Ver, selecione Caixa de Ferramentas para apresentar a Caixa de Ferramentas. Adicione dois botões e uma caixa de verificação ao Formulário1.

  6. Defina a propriedade Nome da caixa de verificação para FillWithStrings.

  7. Faça duplo clique em Botão1. A janela de código do Formulário é exibida.

  8. Adicione o seguinte à parte superior de Formulário1.vb:

    Imports Microsoft.Office.Interop
    
    
  9. Na janela do código, substitua o seguinte código

     Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
    End Sub
    

    com:

     'Keep the application object and the workbook object global, so you can  
     'retrieve the data in Button2_Click that was set in Button1_Click.
     Dim objApp As Excel.Application
     Dim objBook As Excel._Workbook
    
    Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
         Dim objBooks As Excel.Workbooks
         Dim objSheets As Excel.Sheets
         Dim objSheet As Excel._Worksheet
         Dim range As Excel.Range
    
    ' Create a new instance of Excel and start a new workbook.
         objApp = New Excel.Application()
         objBooks = objApp.Workbooks
         objBook = objBooks.Add
         objSheets = objBook.Worksheets
         objSheet = objSheets(1)
    
    'Get the range where the starting cell has the address
         'm_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
         range = objSheet.Range("A1", Reflection.Missing.Value)
         range = range.Resize(5, 5)
    
    If (Me.FillWithStrings.Checked = False) Then
             'Create an array.
             Dim saRet(5, 5) As Double
    
    'Fill the array.
             Dim iRow As Long
             Dim iCol As Long
             For iRow = 0 To 5
                 For iCol = 0 To 5
    
    'Put a counter in the cell.
                     saRet(iRow, iCol) = iRow * iCol
                 Next iCol
             Next iRow
    
    'Set the range value to the array.
             range.Value = saRet
    
    Else
             'Create an array.
             Dim saRet(5, 5) As String
    
    'Fill the array.
             Dim iRow As Long
             Dim iCol As Long
             For iRow = 0 To 5
                 For iCol = 0 To 5
    
    'Put the row and column address in the cell.
                     saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()
                 Next iCol
             Next iRow
    
    'Set the range value to the array.
             range.Value = saRet
         End If
    
    'Return control of Excel to the user.
         objApp.Visible = True
         objApp.UserControl = True
    
    'Clean up a little.
         range = Nothing
         objSheet = Nothing
         objSheets = Nothing
         objBooks = Nothing
     End Sub
    
    
  10. Regresse à vista Estrutura do Formulário1 e, em seguida, faça duplo clique em Botão2.

  11. Na janela do código, substitua o seguinte código

    Private Sub Button2_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button2.Click
    
    End Sub
    

    com:

    Private Sub Button2_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button2.Click
        Dim objSheets As Excel.Sheets
        Dim objSheet As Excel._Worksheet
        Dim range As Excel.Range
    
    'Get a reference to the first sheet of the workbook.
        On Error Goto ExcelNotRunning
        objSheets = objBook.Worksheets
        objSheet = objSheets(1)
    
    ExcelNotRunning:
        If (Not (Err.Number = 0)) Then
            MessageBox.Show("Cannot find the Excel workbook.  Try clicking Button1 to " + _
            "create an Excel workbook with data before running Button2.", _
            "Missing Workbook?")
    
    'We cannot automate Excel if we cannot find the data we created, 
            'so leave the subroutine.
            Exit Sub
        End If
    
    'Get a range of data.
        range = objSheet.Range("A1", "E5")
    
    'Retrieve the data from the range.
        Dim saRet(,) As Object
        saRet = range.Value
    
    'Determine the dimensions of the array.
        Dim iRows As Long
        Dim iCols As Long
        iRows = saRet.GetUpperBound(0)
        iCols = saRet.GetUpperBound(1)
    
    'Build a string that contains the data of the array.
        Dim valueString As String
        valueString = "Array Data" + vbCrLf
    
    Dim rowCounter As Long
        Dim colCounter As Long
        For rowCounter = 1 To iRows
            For colCounter = 1 To iCols
    
    'Write the next value into the string.
                valueString = String.Concat(valueString, _
                    saRet(rowCounter, colCounter).ToString() + ", ")
    
    Next colCounter
    
    'Write in a new line.
            valueString = String.Concat(valueString, vbCrLf)
        Next rowCounter
    
    'Report the value of the array.
        MessageBox.Show(valueString, "Array Values")
    
    'Clean up a little.
        range = Nothing
        objSheet = Nothing
        objSheets = Nothing
    End Sub
    
    

Testar o Cliente de Automatização

  1. Prima F5 para criar e executar o programa de exemplo.
  2. Clique em Botão1. O Microsoft Excel é iniciado com um novo livro e as células A1:E5 da primeira livro são preenchidas com dados numéricos de uma matriz.
  3. Clique em Botão2. O programa obtém os dados nas células A1:E5 numa nova matriz e apresenta os resultados numa caixa de mensagem.
  4. Selecione FillWithStrings e, em seguida, clique em Botão1 para preencher as células A1:E5 com os dados da cadeia.

Referências

Para obter informações adicionais sobre como utilizar matrizes para definir e obter dados do Excel com versões anteriores do Visual Studio, clique nos números do artigo abaixo para ver o artigo na Base de Dados de Conhecimento Microsoft:

247412 INFORMAÇÕES: Métodos para Transferir Dados para o Excel a partir do Visual Basic