Cara menambahkan dan menjalankan makro VBA secara dinamis dari Visual Basic

Berlaku Untuk
Microsoft Office Professional Edition 2003 Excel 2010

Ringkasan

Saat mengotomatisasi produk Office dari Visual Basic, mungkin berguna untuk memindahkan sebagian kode ke dalam modul Microsoft Visual Basic for Applications (VBA) yang dapat berjalan di dalam ruang proses server. Hal ini dapat meningkatkan kecepatan eksekusi keseluruhan untuk aplikasi Anda dan membantu meringankan masalah jika server hanya melakukan tindakan ketika panggilan dilakukan dalam proses.

 Artikel ini menunjukkan cara menambahkan modul VBA secara dinamis ke aplikasi Office yang berjalan dari Visual Basic, lalu panggil makro untuk mengisi lembar kerja dalam proses.

Informasi Selengkapnya

Contoh berikut ini menunjukkan penyisipan modul kode ke Microsoft Excel, tetapi Anda bisa menggunakan teknik yang sama untuk Word dan PowerPoint karena keduanya menggabungkan mesin VBA yang sama.

 Sampel menggunakan file teks statis untuk modul kode yang disisipkan ke Excel. Anda mungkin ingin mempertimbangkan untuk memindahkan kode ke dalam file sumber daya yang dapat dikompile ke dalam aplikasi, lalu mengekstrak ke file sementara saat diperlukan pada waktu proses. Ini akan membuat proyek lebih mudah dikelola untuk distribusi ulang.

 Dimulai dengan Microsoft Office XP, pengguna harus memberikan akses ke model objek VBA sebelum kode Otomatisasi yang ditulis untuk memanipulasi VBA akan berfungsi. Ini adalah fitur keamanan baru dengan Office XP. Untuk informasi selengkapnya, silakan lihat artikel Basis pengetahuan berikut ini:

282830 Programmatic Access to Office XP VBA Project ditolak

Langkah-langkah untuk menyusun sampel

  1. Pertama, buat file teks baru bernama KbTest.bas (tanpa ekstensi .txt). Ini adalah modul kode yang akan kami sisipkan ke Excel pada run-time.

  2. Dalam file teks, tambahkan baris kode berikut:

       Attribute VB_Name = "KbTest"
    
       ' Your Microsoft Visual Basic for Applications macro function takes 1 
       ' parameter, the sheet object that you are going to fill.
    
       Public Sub DoKbTest(oSheetToFill As Object)
          Dim i As Integer, j As Integer
          Dim sMsg As String
          For i = 1 To 100
             For j = 1 To 10
    
                sMsg = "Cell(" & Str(i) & "," & Str(j) & ")"
                oSheetToFill.Cells(i, j).Value = sMsg
             Next j
          Next i
       End Sub
    
    
  3. Simpan file teks ke direktori C:\KbTest.bas, lalu tutup file.

  4. Mulai Visual Basic dan buat proyek standar. Formulir1 dibuat secara default.

  5. Pada menu Proyek , klikReferensi, lalu pilih tipe versi pustaka yang sesuai yang memungkinkan Anda menggunakan pengikat awal ke Excel.

    Misalnya, pilih salah satu hal berikut ini:

    • Untuk Microsoft Office Excel 2007, pilih pustaka 12.0.
    • Untuk Microsoft Office Excel 2003, pilih pustaka 11.0.
    • Untuk Microsoft Excel 2002, pilih pustaka 10.0.
    • Untuk Microsoft Excel 2000, pilih pustaka 9.0.
    • Untuk Microsoft Excel 97, pilih pustaka 8.0.
  6. Tambahkan tombol ke Formulir1, dan letakkan kode berikut ini di handler untuk acara Klik tombol:

       Private Sub Command1_Click()
          Dim oXL As Excel.Application
          Dim oBook As Excel.Workbook
          Dim oSheet As Excel.Worksheet
          Dim i As Integer, j As Integer
          Dim sMsg As String
    
        ' Create a new instance of Excel and make it visible.
          Set oXL = CreateObject("Excel.Application")
          oXL.Visible = True
    
        ' Add a new workbook and set a reference to Sheet1.
          Set oBook = oXL.Workbooks.Add
          Set oSheet = oBook.Sheets(1)
    
        ' Demo standard Automation from out-of-process,
        ' this routine simply fills in values of cells.
          sMsg = "Fill the sheet from out-of-process"
          MsgBox sMsg, vbInformation Or vbMsgBoxSetForeground
    
          For i = 1 To 100
             For j = 1 To 10
                sMsg = "Cell(" & Str(i) & "," & Str(j) & ")"
                oSheet.Cells(i, j).Value = sMsg
             Next j
          Next i
    
        ' You're done with the first test, now switch sheets
        ' and run the same routine via an inserted Microsoft Visual Basic 
        ' for Applications macro.
          MsgBox "Done.", vbMsgBoxSetForeground
          Set oSheet = oBook.Sheets.Add
          oSheet.Activate
    
          sMsg = "Fill the sheet from in-process"
          MsgBox sMsg, vbInformation Or vbMsgBoxSetForeground
    
        ' The Import method lets you add modules to VBA at
        ' run time. Change the file path to match the location
        ' of the text file you created in step 3.
          oXL.VBE.ActiveVBProject.VBComponents.Import "C:\KbTest.bas"
    
        ' Now run the macro, passing oSheet as the first parameter
          oXL.Run "DoKbTest", oSheet
    
        ' You're done with the second test
          MsgBox "Done.", vbMsgBoxSetForeground
    
        ' Turn instance of Excel over to end user and release
        ' any outstanding object references.
          oXL.UserControl = True
          Set oSheet = Nothing
          Set oBook = Nothing
          Set oXL = Nothing
    
       End Sub
    
    
  7. Untuk Excel 2002 dan untuk versi Excel yang lebih baru, Anda harus mengaktifkan akses proyek VBA. Untuk melakukan ini, gunakan salah satu metode berikut ini:

    • Di Excel 2007, klik Tombol Microsoft Office, lalu klik Opsi Excel. Klik Pusat Kepercayaan, lalu klik Pengaturan Pusat Kepercayaan. Klik Pengaturan Makro, klik untuk memilih kotak centang Percayai Akses ke model objek proyek VBA , lalu klik OK dua kali.
    • Di Excel 2003 dan di versi Excel yang lebih lama, arahkan ke Makro pada menu Alat , lalu klik Keamanan. Dalam kotak dialog Keamanan , klik tab Sumber Tepercaya , lalu klik untuk memilih kotak centang Percayai akses ke Proyek Visual Basic .
  8. Jalankan proyek Visual Basic.

Referensi

Untuk informasi selengkapnya tentang Otomatisasi Office dari Visual Basic, silakan lihat situs Dukungan Pengembangan Office di alamat berikut ini:

http://support.microsoft.com/ofd