שתף באמצעות


כיצד להפוך את Excel מ- Visual Basic .NET לאוטומטי למילוי או להשגת נתונים בטווח באמצעות מערכים

סיכום

מאמר זה מדגים כיצד להפוך את Microsoft Excel לאוטומטי וכיצד למלא טווח מרובה תאים במערך ערכים. מאמר זה גם מדגים כיצד לאחזר טווח מרובה תאים כמערך באמצעות אוטומציה.

מידע נוסף

כדי למלא טווח מרובה תאים מבלי לאכלס תאים בזה אחר זה, באפשרותך להגדיר את המאפיין ערך של אובייקט טווח למערך דו-ממדי. בדומה לכך, ניתן לאחזר מערך דו-ממדי של ערכים עבור תאים מרובים בו-זמנית באמצעות המאפיין ערך. השלבים הבאים מדגימים תהליך זה הן עבור הגדרה והן אחזור של נתונים באמצעות מערכים דו-ממדיים.

בניית לקוח אוטומציה עבור Microsoft Excel

  1. הפעל את Microsoft Visual Studio .NET.

  2. בתפריט קובץ, לחץ על חדש ולאחר מכן לחץ על פרוייקט. בחר יישום Windows מסוגי הפרוייקטים של Visual Basic. כברירת מחדל, Form1 נוצר.

  3. הוסף הפניה לספריית האובייקטים של Microsoft Excel. לשם כך, בצע את הפעולות הבאות:

    1. בתפריט פרוייקט, לחץ על הוסף הפניה.
    2. בכרטיסיה COM, אתר את ספריית האובייקטים של Microsoft Excel ולאחר מכן לחץ על בחר.

    הערה Microsoft Office 2007 ו- Microsoft Office 2003 כוללים הרכבות Interop ראשיות (PIAs). Microsoft Office XP אינו כולל PIAs, אך ניתן להוריד אותם.

  4. לחץ על אישור בתיבת הדו-שיח הוספת הפניות כדי לקבל את הבחירות שלך. אם תתבקש ליצור עטופים עבור הספריות שבחרת, לחץ על כן.

  5. בתפריט תצוגה, בחר ארגז כלים כדי להציג את ארגז הכלים. הוסף שני לחצנים ותיבת סימון לטופס1.

  6. הגדר את המאפיין Name עבור תיבת הסימון ל- FillWithStrings.

  7. לחץ פעמיים על לחצן1. חלון הקוד עבור הטופס מופיע.

  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
    

    עם:

     '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 ולאחר מכן לחץ פעמיים על לחצן2.

  11. בחלון הקוד, החלף את הקוד הבא

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

    עם:

    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
    
    

בדוק את לקוח האוטומציה

  1. הקש F5 כדי לבנות ולהפעיל את התוכנית לדוגמה.
  2. לחץ על לחצן1. Microsoft Excel מופעל עם חוברת עבודה חדשה, ותאים A1:E5 בגליון העבודה הראשון מאוכלסים בנתונים מספריים ממערך.
  3. לחץ על לחצן2. התוכנית מאחזרת את הנתונים בתאים A1:E5 למערך חדש ומציגה את התוצאות בתיבת הודעה.
  4. בחר FillWithStrings ולאחר מכן לחץ על Button1 כדי למלא את התאים A1:E5 ותוני המחרוזת.

הפניות

לקבלת מידע נוסף על השימוש במערכים כדי להגדיר ולאחזר נתוני Excel עם גירסאות קודמות של Visual Studio, לחץ על מספרי המאמרים שלהלן כדי להציגם מתוך מאגר הידע Microsoft Knowledge Base:

247412 נוסף: שיטות להעברת נתונים ל- Excel מ- Visual Basic