VBA Excel

download VBA Excel

of 21

description

VBA excel

Transcript of VBA Excel

  • BelajarVBApadaMSExcel2003/2007

    BELAJAR VBA DALAM EXCEL DukunganuntukOffice2003berakhirpada8April2014Microsoftmengakhiridukungan untukOffice 2003 pada8April2014.Perubahan inidapatmempengaruhipemutakhiranperangkatlunakdanopsikeamananAnda.

    MEMULAI MAKRO EXCEL

    Untuk membuat Makro Excel Anda harus membuka sebuah file Microsoft Excel (contohnya contoh.xls). Selanjutnya Anda dapat membuat Makro dengan beberapa cara, seperti dipaparkan dalam paragraf-paragraf di bawah ini. 1. CREATE MACRO (ALT + F8)

    Pertama-tama, buatlah/bukalah sebuah file Microsoft Excel yang sudah diberi nama (misal: contoh.xls). Pada menu Tools, tunjuk Macro lalu tunjuk Macros, kemudian klik kiri Mouse (atau tekan Alt +F8),

    sehingga muncul tampilan seperti berikut,

  • BelajarVBApadaMSExcel2003/2007

    Ketik nama Makro yang dikehendaki pada isian Macro name, contohnya: coba. Maka tombol create akan aktif, seperti pada gambar di bawah ini:

    Klik tombol create, sehingga tampilan berikut akan muncul

    maka Anda telah membuat sebuah Modul Visual Basic for Aplication (VBA) bernama Module1 dan sebuah prosedur VBA bernama coba().

    Anda dapat memilih agar Makro ini bekerja: di seluruh file Excel yang terbuka (All Open Workbooks), hanya pada file yang sedang Anda buka (This Workbooks), atau pada file contoh.xls, file Excel dimana Anda membuat Makro-nya. Dengan cara memilih pilihan tersebut pada Macros In.

  • BelajarVBApadaMSExcel2003/2007

    2. RECORD NEW MACRO

    Cara kedua ini merupakan yang lebih praktis sehingga dapat menjadi lebih cepat, sebab dengan cara ini kita dapat membuat kode Visual Basic tanpa harus menuliskannya. Pada dasarnya, semua operasi Excel dapat dilakukan oleh Macros. Operasi itu dapat dicatat oleh Macros melalui Record New Macros. Kemudian kita dapat mengubah kode-kode VBA yang dihasilkan oleh operasi yang tercatat tersebut.

    Untuk memulai mencatat Makro maka pada menu Tools, sorot Macro kemudian sorot Record New Macros lalu klik kiri tetikus (mouse),

    sehingga tampilan di bawah ini akan muncul,

  • BelajarVBApadaMSExcel2003/2007

    Kolom isian Macro name: adalah tempat Anda memberi nama Macro (misal: Macro1). Kolom Shortcut key disediakan bila Anda hendak membuat shortcut key dari keyboard

    (Ctrl+ tombol keypad yang Anda inginkan). Kolom isian Store Macro in merupakan kolom isian untuk menentukan dimana macro

    akan disimpan, pilihannya adalah This Workbook, New Workbook dan Personal Macro Workbook.

    Dan, kolom Description disediakan, bila Anda ingin memberi penjelasan singkat mengenai Macro yang akan Anda catat.

    Sebagai contoh, kita akan mencatat Macro bernama ok, yang mencatat operasi Excel berupa pengisian sel A1 dengan kata ok, dan mempunyai shortcut key Ctrl + q.

    Pertama-tama, lakukan langkah-langkah yang telah disebutkan seperti di atas sehingga muncul tampilan sebagai berikut:

    Lalu tekan tombol OK. Pencatatan masih terus berlangsung (sedang dilakukan), maka isilah sel A1 dengan kata ok,

    lalu pada Menu Tools, sorot Macro, kemudian tekan Stop Recording dan pencatatan akan berhenti.

  • BelajarVBApadaMSExcel2003/2007

    Untuk melihat kode VBA yang telah tercatat (recorded), maka pada menu Tools sorotlah Macro,

    Pilihlah ok pada Macro name: lalu tekan tombol Edit, sehingga akan muncul tampilan sebagai berikut,

  • BelajarVBApadaMSExcel2003/2007

    Cobalah untuk mengubah Range(A1) menjadi Range(A2), simpan dengan menekan gambar disket atau Ctrl + S. Kembali ke contoh.xls, tekan Ctrl + q dari Keyboard, dan lihatlah apa yang terjadi..?

    3. VISUAL BASIC EDITOR (ALT +F11)

    Bila Anda sudah mengenal pemograman Visual BASIC, maka cara ini tidaklah sulit. Bahkan kadang-kadang Anda akan sering melakukannya. Untuk menampilkan Visual Basic Editor Anda cukup menekan Alt+F11 maka tampilan berikut akan muncul,

  • BelajarVBApadaMSExcel2003/2007

  • BelajarVBApadaMSExcel2003/2007

    SINTAKS PENGKODEAN VBA DALAM EXCEL DukunganuntukOffice2003berakhirpada8April2014Microsoftmengakhiridukungan untukOffice 2003 pada8April2014.Perubahan inidapatmempengaruhipemutakhiranperangkatlunakdanopsikeamananAnda.

    MEMULAI KODE PROGRAM VBA DALAM EXCEL

    Pada saat memulai membuat program VB (Visual Basic), diperlukan beberapa pernyataan deklarasi variabel-variabel yang di dalamnya terkaik dengan jenisnya: INTEGER, REAL, atau lainnya. 1. PENGGUNAAN DIM

    Deklarasi variabel Boolean: Dim finished As Boolean Dim loop, reached As Boolean

    Deklarasi bilangan/skalar INTEGER: Dim I As Integer Dim i, j As Integer Dim c As Integer, i, j As Integer Dim quantity As Integer = 10

    Deklarasi bilangan/skalar REAL presisi tunggal (Single): Dim R As Single Dim a, b, c As Single

    Deklarasi bilangan/skalar REAL presisi ganda (Double): Dim D As Double Dim R As Double = 3.535 Dim x, y As Double

    Deklarasi larik (array) INTEGER: Dim Ivec(10) As Integer Dim Ivec(0 to 10) As Integer Dim Imatriks(10,10) As Integer

    Deklarasi larik (array) REAL presisi tunggal: Dim Svec(20) As Single Dim Svec(0 to 20) As Single Dim Smatriks (20,20) As Single

    Deklarasi larik (array) REAL presisi ganda: Dim Dvec(20) As Double Dim Dvec(0 to 20) As Double Dim Dmatriks (20,20) As Double

    PERNYATAAN-PERNYATAAN BERULANG DAN BERSANGKAR

    Beberapa pernyataan berulang yang sering dipakai dalam VB adalah: For...Next; Do...While

  • BelajarVBApadaMSExcel2003/2007

    1. SINTAKS

    Pernyataan bersangkar 1-lapis (tunggal/single): Dim i As Integer For i = 1 To 6 Cells(i, 1).Value = 100 Next i

    Explanation: The code lines between For and Next will be executed six times. For i = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i with 1 and jumps back to the For statement. For i = 2, Excel VBA enters the value 100 into the cell at the intersection of row 2 and column 1, etc.

    Note: it is good practice to always indent (tab) the code between the words For and Next. This makes your code easier to read.

    Pernyataan bersangkar 2-lapis (ganda/double):

    Dim i As Integer, j As Integer For i = 1 To 6 For j = 1 To 2 Cells(i, j).Value = 100 Next j Next i

    Explanation: For i = 1 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next j, it increases j with 1 and jumps back to the For j statement. For i = 1 and j = 2, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 2. Next, Excel VBA ignores Next j because j only runs from 1 to 2. When Excel VBA reaches Next i, it increases i with 1 and jumps back to the For i statement. For i = 2 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 2 and column 1, etc.

    Pernyataan bersangkar 3-lapis (triple):

  • BelajarVBApadaMSExcel2003/2007

    Dim c As Integer, i As Integer, j As Integer For c = 1 To 3 For i = 1 To 6 For j = 1 To 2 Worksheets(c).Cells(i, j).Value = 100 Next j Next i Next c

    Explanation: The only change made compared to the code for the double loop is that we have added one more loop and added Worksheets(c). in front of Cells to get the two-dimensional range on the first sheet for c = 1, the second sheet for c = 2 and the third sheet for c = 3.

  • BelajarVBApadaMSExcel2003/2007

    2. SINTAKS

    Selain pernyataan , dikenal pula pernyataan bersangkar berupa dengan sintaks penulisannya seperti diberikan dalam dua contoh berikut:

    Dim i As Integer i = 1 Do While i < 6 Cells(i, 1).Value = 20 i = i + 1 Loop

    Explanation: as long as i is lower than 6, Excel VBA enters the value 20 into the cell at the intersection of row i and column 1 and increments i by 1. In Excel VBA (and in other programming languages), the symbol '=' means becomes. It does not mean equal. So i = i + 1 means i becomes i + 1. In other words: take the present value of i and add 1 to it. For example, if i = 1, i becomes 1 + 1 = 2. As a result, the value 20 will be placed into column A five times (not six because Excel VBA stops when i equals 6).

    Dim i As Integer i = 1 Do While Cells(i, 1).Value "" Cells(i, 2).Value = Cells(i, 1).Value + 10 i = i + 1 Loop

    Explanation: as long as Cells(i, 1).Value is not empty ( means not equal to), Excel VBA enters the value into the cell at the intersection of row i and column 2, that is 10 higher than the value in the cell at the intersection of row i and column 1. Excel VBA stops when i equals 7 because Cells(7, 1).Value is empty. This is a great way to loop through any number of rows on a worksheet.

  • BelajarVBApadaMSExcel2003/2007

    Function

    Function If you want Excel VBA to perform a task that returns a result, you can use a function. Place a function into a module (In the Visual Basic Editor, click Insert, Module). For example, the function with name Area.

    Function Area(x As Double, y As Double) As Double Area = x * y End Function

    Dim z As Double z = Area(3, 5) + 2 MsgBox z

    Sub If you want Excel VBA to perform some actions, you can use a sub. Place a sub into a module (In the Visual Basic Editor, click Insert, Module). For example, the sub with name Area.

    Sub Area(x As Double, y As Double) MsgBox x * y End Sub

    Explanation: This sub has two arguments (of type Double). It does not have a return type! You can refer to this sub (call the sub) from somewhere else in your code by simply using the name of the sub and giving a value for each argument.

    Private Function CheckIfPrime(ByVal number As Integer) As Boolean If number < 2 Then Return False Else ' The root and highCheck variables can be accessed ' only within the Else block. Different variables ' with the same names could be declared outside of ' the Else block. Dim root As Double = Math.Sqrt(number) Dim highCheck As Integer = Convert.ToInt32(Math.Truncate(root)) ' The div variable can be accessed only within ' the For...Next block. For div As Integer = 2 To highCheck If number Mod div = 0 Then Return False End If Next Return True End If End Function

  • BelajarVBApadaMSExcel2003/2007

  • BelajarVBApadaMSExcel2003/2007

    MAKRO VBA UNTUK GABUNGKAN KOLOM DATA DALAM EXCEL DukunganuntukOffice2003berakhirpada8April2014Microsoftmengakhiridukungan untukOffice 2003 pada8April2014.Perubahan inidapatmempengaruhipemutakhiranperangkatlunakdanopsikeamananAnda.

    RINGKASAN

    Dalam Microsoft Excel, Anda dapat menggunakan makro untuk pengabungan data dalam dua kolom yang bersebelahan dan menampilkan hasil di kolom sebelah kanan kolom yang berisi data Anda. Artikel ini berisi contoh Microsoft Visual Basic untuk aplikasi (VBA) makro (Sub prosedur) untuk melakukan hal ini.

    HAL YANG PERLU DIKETAHUI

    Microsoft menyediakan pemrogaman hanya untuk ilustrasi, tanpa garansi baik tersurat maupun tersirat. Ini mencakup, namun tidak terbatas pada, garansi yang tersirat dapat diperjualbelikan atau kesesuaian untuk tujuan tertentu.

    Artikel ini menganggap bahwa Anda sudah terbiasa dengan bahasa pemrograman yang muncul dan alat-alat yang digunakan untuk membuat dan prosedur debug.

    Teknisi dukungan Microsoft dapat membantu menjelaskan fungsionalitas prosedur tertentu. Namun, mereka tidak akan mengubah contoh tersebut untuk memberikan fungsionalitas tambahan atau menyusun prosedur untuk memenuhi persyaratan khusus Anda.

    CONTOH PEMROGRAM MAKRO VBA (VISUAL BASIC FOR APPLICATIONS)

    Sebagai contoh untuk pemrograman VBA dalam Microsoft Excel (Office 2003 atau 2007) disajikan seperti di bawah ini:

    SubConcatColumns()DoWhileActiveCell""'Loopsuntiltheactivecellisblank.'The"&"musthaveaspaceonbothsidesoritwillbe'treatedasavariabletypeoflonginteger.ActiveCell.Offset(0,1).FormulaR1C1=_ActiveCell.Offset(0,1)&""&ActiveCell.Offset(0,0)ActiveCell.Offset(1,0).SelectLoopEnd Sub

    Catatan: pernyataan ActiveCell.Offset (0, 1).FormulaR1C1 dapat digantikan dengan pernyataan ActiveCell.Offset (0, 1).Formula.Mereka dapat digunakan dengan sukses sama jika Anda menggunakan teks dan hanya angka (bukan formula). R1C1 yang digunakan di akhir pernyataan pertama merujuk ke baris satu, kolom satu dan adalah bentuk yang digunakan dalam contoh dalam bantuan.

  • BelajarVBApadaMSExcel2003/2007

    CARA MENGGUNAKAN MAKRO DI MICROSOFT OFFICE EXCEL 2007/2010

    Penggunaan MAKRO dalam Microsoft Office Excel 2007 untuk pemrograman VBA dimaksud seperti di atas, caranya adalah sebagai berikut:

    1. Membuka workbook yang berisi data. 2. Tekan ALT + F11 untuk memulai Editor Visual Basic. 3. Masukkan menu, klik modul untuk menyisipkan modul. Ketik makro dalam jendela kode

    modul. 4. Pada File menu, klik tutup dan kembali ke Microsoft Excel. 5. Pilih lembar kerja yang berisi data yang ingin Anda gabungkan. 6. Klik sel atas di kolom sebelah kanan data yang ingin Anda gabungkan. Sebagai contoh, jika

    sel A1:A100 dan B1:B100 berisi data, klik sel B1. 7. Klik tab pengembang. Apabila tab pengembang tidak ditampilkan, ikuti langkah-langkah

    berikut: a. Klik Tombol Microsoft Office, dan kemudian klik Opsi Excel. b. Klik populer. c. Klik untuk memilih kotak centang Tampilkan tab pengembang pada pita. d. Klik OK untuk menutup kotak dialog Opsi Excel.

    8. Klik makro dalam kelompok kode. 9. Pilih ConcatColumns makro, dan kemudian klik Jalankan.

    1. Open the workbook that contains the data. 2. Press ALT+F11 to start the Visual Basic Editor. 3. On the Insert menu, click Module to insert a module. Type the macro in the module's code

    window.

    4. On the File menu, click Close and Return to Microsoft Excel. 5. Select the worksheet that contains the data that you want to concatenate. 6. Click the top cell in the right column of data that you want to concatenate. For example, if

    cells A1:A100 and B1:B100 contain data, click cell B1.

    7. Click the Developer tab. If the Developer tab is not displayed, follow these steps: a. Click the Microsoft Office Button, and then click Excel Options. b. Click Popular. c. Click to select the Show Developer tab in the Ribbon check box. d. Click OK to close the Excel Options dialog box.

    8. Click Macros in the Code group. 9. Select the ConcatColumns macro, and then click Run.

  • BelajarVBApadaMSExcel2003/2007

    CARA MENGGUNAKAN MAKRO DI MICROSOFT OFFICE EXCEL 2003

    Untuk MAKRO dalam Microsoft Office Excel 2003, maka cara penggunaannya untuk pemrograman VBA dimaksud adalah sebagai berikut:

    1. Membuka workbook yang berisi data.

    2. Tekan ALT + F11 untuk memulai Editor Visual Basic.

    3. Klik menu Insert, kemudian klik Module untuk menyisipkan modul. Ketik makro dalam jendela kode modul.

    4. Pada menu File, klik Close and Return to Microsoft Excel.

    5. Pilih worksheet yang berisi data yang ingin Anda gabungkan.

    6. Klik sel atas (the top cell) di kolom sebelah kanan data yang ingin Anda gabungkan. Sebagai contoh, jika sel A1:A100 dan B1:B100 berisi data, klik sel B1.

    7. Pada menu Tools, arahkan ke Macros, dan kemudian klik Macro. Pilih ConcatColumns makro, dan kemudian klik Run.

    1. Open the workbook that contains the data. 2. Press ALT+F11 to start the Visual Basic Editor. 3. On the Insert menu, click Module to insert a module. Type the macro in the module's code

    window.

    4. On the File menu, click Close and Return to Microsoft Excel. 5. Select the worksheet that contains the data that you want to concatenate. 6. Click the top cell in the right column of data that you want to concatenate. For example, if

    cells A1:A100 and B1:B100 contain data, click cell B1.

    7. On the Tools menu, point to Macros, and then click Macro. Select the ConcatColumns macro, and then click Run.

    REFERENSI

    Untuk informasi selengkapnya tentang Visual Basic untuk aplikasi, klik nomor artikel berikut ini untuk melihat artikel di Pangkalan Pengetahuan Microsoft:

    226118 Daftar sumber daya yang tersedia untuk membantu Anda mempelajari Visual Basic untuk aplikasi pemrograman

  • BelajarVBApadaMSExcel2003/2007

    BEBERAPA CONTOH KODE VBA DALAM PEMROGRAMAN DukunganuntukOffice2003berakhirpada8April2014Microsoftmengakhiridukungan untukOffice 2003 pada8April2014.Perubahan inidapatmempengaruhipemutakhiranperangkatlunakdanopsikeamananAnda.

    AUTO RUN

    Ada beberapa cara untuk membuat macros yang kita buat berjalan secara otomatis ketika pertama kali membuka workbook. Yang pertama adalah Auto Open Method, yang diletakkan di modules, kedua adalah Workbook Open Method, yang diletakkan di pada obyek Workbook (lihat penjelasan pada langkah 3). Dua contoh kode berikut akan menampilkan pesan hi ketika Workbook pertama kali dibuka.

    Sub Auto_Open( ) Msgbox hi End Sub

    Private Sub Workbook_Open( ) Msgbox hi End Sub

    MENGHITUNG ROWS, COLUMNS DAN SHEET

    Kode berikut digunakan untuk menghitung berapa jumlah rows (baris) atau columns(kolom) yang telah kita sorot dengan kursor.

    Sub Hitung( ) hitung_baris = Selection.Rows.Count hitung_kolom = Selection.Columns.Count MsgBox hitung_baris & " " & hitung_kolom End Sub Sub hitung_sheet( ) hitung_sheet = Application.Sheets.Count Msgbox hitung_sheet End Sub

    COPY RANGE

    Contoh berikut akan meng-copy range A1 sampai A3 ke D1 sampai D3

    Sub Kopi_Range( ) Range (A1:A3).Copy Destination:=Range(D1:D3) End Sub

  • BelajarVBApadaMSExcel2003/2007

    WAKTU SAAT INI

    Contoh berikut akan menampilkan waktu pada saat ini

    Sub sekarang( ) Range (A1)= Now End Sub

    MENGETAHUI POSISI SEL YANG SEDANG AKTIF

    Contoh berikut program VBA untuk mengetahui posisi sel yang sedang aktif

    Sub posisi( ) baris = ActiveCell.Row kolom = ActiveCell.Column Msgbox baris & , & kolom End Sub

    MENGHAPUS BARIS YANG KOSONG

    Contoh berikut dapat digunakan untuk menghapus baris yang kosong:

    Sub hapus_baris_kosong( ) Rng = Selection.Rows.Count ActiveCell.Offset(0, 0).Select For i = 1 To Rng If ActiveCell.Value = "" Then Selection.EntireRow.Delete Else ActiveCell.Offset(1, 0).Select End If Next I End Sub

    MENEBALKAN DAN MEWARNAI HURUF (FONT)

    Contoh berikut akan menebalkan dan memberi warna merah pada huruf dimana sel sedang aktif.

    Sub tebal_merah( ) Selection.Font.Bold = True Selection.Font.ColorIndex = 3 End Sub

  • BelajarVBApadaMSExcel2003/2007

    MENGIRIMKAN WORKBOOK MELALUI EMAIL

    Contoh berikut dapat mengirimkan workbook melalui email:

    Sub email( ) ActiveWorkbook.SendMail recipients:= [email protected] End Sub

    FUNGSI EXCEL

    Menggunakan fungsi bawaan Excel dalam VBE hampir sama dengan menggunakannya dalam Excel. Misal fungsi round untuk membulatkan sebuah angka, dalam spreadsheet akan terlihat seperti di bawah ini:

    = round(1.2367, 2)

    Dalam VBE Anda cukup menggunakan Application kemudian disusul fungsi yang akan dipakai.

    Sub bulat( ) ActiveCell = Application.Round(ActiveCell, 2) End Sub

    MENGHAPUS NAMA-NAMA RANGE

    Contoh berikut akan menghapus semua nama-nama range di dalam workbook Anda

    Sub hapus_nama_range( ) Dim NameX As Name For Each NameX In Names ActiveWorkbook.Names(NameX.Name).Delete Next NameX End Sub

    LAYAR BERKEDIP

    Program dalam macros yang sedang berjalan dapat membuat layar berkedip-kedip, untuk menghentikannya Anda dapat menyisipkan kode berikut.

    Application.ScreenUpdating = False MENUJU RANGE TERTENTU

    Untuk menuju suatu range tertentu, kode-kode berikut dapat digunakan.

    Application.Goto Reference:=A1 atau

    Range(A1).Select

  • BelajarVBApadaMSExcel2003/2007

    MENUJU SHEET TERTENTU

    Untuk menuju worksheet tertentu, dapat gunakan kode-kode berikut 8ntuk menuju Sheet terdepan (nomor 1):

    Sheets(1).Select atau

    Sheet1.Select

    dan untuk menuju Sheet bernama coba, dapat digunakan kode berikut:

    Sheet(coba).Select MENYEMBUNYIKAN WORKSHEET

    Kode berikut dapat digunakan untuk menyembunyikan Sheet1

    Sheet1.Visible = xlSheetVeryHidden Catatan: Pengguna tidak dapat membuka sheet yang telah disembunyikan dengan cara ini,

    melainkan hanya dengan kode VBE sheet dapat dibuka kembali. INPUT BOX

    Kode berikut berguna untuk memunculkan Input Box

    InputBox(Masukkan Nama) MENYISIPKAN BARIS DAN KOLOM

    Kode berikut dapat digunakan untuk menyisipkan baris di atas range A1,

    Range(A1).Select Selection.EntireRow.Insert

    sedangkan yang berikut akan menyisipkan satu kolom di samping kiri range A1,

    Range(A1).Select Selection.EntireColumn.Insert

    MENGATUR ULANG UKURAN RANGE

    Kode berikut digunakan untuk mengatur ulang ukuran range:

    Selection.Resize(7,7).Select

  • BelajarVBApadaMSExcel2003/2007

    MEMBERI NAMA RANGE

    Kode berikut digunakan untuk memberi nama range:

    Selection.Name = nama MENYIMPAN FILE

    Kode berikut berguna untuk menyimpan file (Save) tanpa memberi nama:

    ActiveWorkbook.Save

    Sedangkan bila Anda hendak memberi nama (Save As), gunakan kode berikut,

    ActiveWorkbook.SaveAs Filename:=C:\coba.xls

    Belajar VBA dalam ExcelSintaks Pengkodean VBA dalam ExcelMakro VBA untuk Gabungkan kolom data dalam ExcelBeberapa Contoh Kode Vba Dalam Pemrograman