Visual Basic .NET에서 Excel을 자동화하여 배열을 사용하여 범위에서 데이터를 채우거나 가져오는 방법

요약

이 문서에서는 Microsoft Excel을 자동화하는 방법과 여러 셀 범위를 값 배열로 채우는 방법을 보여 줍니다. 이 문서에서는 Automation을 사용하여 다중 셀 범위를 배열로 검색하는 방법도 보여 줍니다.

추가 정보

셀을 한 번에 하나씩 채우지 않고 다중 셀 범위를 채우려면 Range 개체의 Value 속성을 2차원 배열로 설정할 수 있습니다. 마찬가지로 Value 속성을 사용하여 여러 셀에 대해 2차원 값 배열을 한 번에 검색할 수 있습니다. 다음 단계에서는 2차원 배열을 사용하여 데이터를 설정하고 검색하는 프로세스를 보여 줍니다.

Microsoft Excel용 Automation 클라이언트 빌드

  1. Microsoft Visual Studio .NET을 시작합니다.

  2. [파일] 메뉴에서 [새로 만들기]를 클릭한 다음 [프로젝트]를 클릭합니다. Visual Basic 프로젝트 유형에서 Windows 애플리케이션을 선택합니다. 기본적으로 Form1이 만들어집니다.

  3. Microsoft Excel 개체 라이브러리에 대한 참조를 추가합니다. 이렇게 하려면 다음과 같이 하십시오.

    1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.
    2. COM 탭에서 Microsoft Excel 개체 라이브러리를 찾은 다음 선택을 클릭합니다.

    참고 Microsoft Office 2007 및 Microsoft Office 2003에는 IA(기본 Interop 어셈블리)가 포함됩니다. Microsoft Office XP에는 PIA가 포함되지 않지만 다운로드할 수 있습니다.

  4. [참조 추가] 대화 상자에서 [확인]을 클릭하여 선택 내용을 적용합니다. 선택한 라이브러리에 대한 래퍼를 생성하라는 메시지가 표시되면 [예]를 클릭합니다.

  5. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시합니다. Form1에 단추 2개와 확인란을 추가합니다.

  6. 확인란의 Name 속성을 FillWithStrings로 설정합니다.

  7. Button1을 두 번 클릭합니다. 폼의 코드 창이 나타납니다.

  8. Form1.vb의 맨 위에 다음을 추가합니다.

    Imports Microsoft.Office.Interop
    
    
  9. 코드 창에서 다음 코드를 바꿉

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

    with:

     '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. Form1의 디자인 보기로 돌아가서 Button2를 두 번 클릭합니다.

  11. 코드 창에서 다음 코드를 바꿉

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

    with:

    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
    
    

Automation 클라이언트 테스트

  1. F5 키를 눌러 샘플 프로그램을 빌드하고 실행합니다.
  2. Button1을 클릭합니다. Microsoft Excel은 새 통합 문서로 시작되며 첫 번째 워크시트의 A1:E5 셀은 배열의 숫자 데이터로 채워집니다.
  3. Button2를 클릭합니다. 프로그램은 셀 A1:E5의 데이터를 새 배열로 검색하고 메시지 상자에 결과를 표시합니다.
  4. FillWithStrings를 선택한 다음 Button1을 클릭하여 셀 A1:E5를 문자열 데이터로 채웁니다.

참조

이전 버전의 Visual Studio에서 배열을 사용하여 Excel 데이터를 설정하고 검색하는 방법에 대한 자세한 내용은 아래 문서 번호를 클릭하여 Microsoft 기술 자료의 문서를 확인합니다.

247412 INFO: Visual Basic에서 Excel로 데이터를 전송하는 방법