Cara menambahkan dan menjalankan makro VBA secara dinamis dari Visual Basic

Berlaku Untuk
Microsoft Office Professional Edition 2003 Excel 2010

Ringkasan

Saat mengotomatiskan produk Office dari Visual Basic, mungkin berguna untuk memindahkan sebagian kode ke dalam modul Microsoft Visual Basic untuk 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 saat panggilan dilakukan dalam proses.

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

Informasi Selengkapnya

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

 Contoh 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 dikompilasi ke dalam aplikasi, lalu mengekstrak ke dalam file sementara bila diperlukan saat menjalankan waktu. Ini akan membuat proyek lebih mudah dikelola untuk redistribusi.

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

282830 Akses terprogram ke Office XP VBA Project ditolak

Langkah-langkah untuk membuat sampel

  1. Pertama, buat file teks baru bernama KbTest.bas (tanpa ekstensi .txt). Ini adalah modul kode yang akan kita masukkan ke Excel saat 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. Form1 dibuat secara default.

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

    Misalnya, pilih salah satu hal berikut:

    • 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 tempatkan kode berikut di penanganan untuk kejadian 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 Excel versi yang lebih baru, Anda harus mengaktifkan Mengakses proyek VBA. Untuk melakukannya, gunakan salah satu metode berikut:

    • 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 Akses Kepercayaan ke model objek proyek VBA , lalu klik OK dua kali.
    • Di Excel 2003 dan 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 Percaya akses ke Visual Basic Project .
  8. Jalankan proyek Visual Basic.

Referensi

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

http://support.microsoft.com/ofd