VBA Excel
VBA Excel
BelajarVBApadaMSExcel2003/2007
Ketik nama Makro yang dikehendaki pada isian Macro name, contohnya: coba. Maka tombol
create akan aktif, seperti pada gambar di bawah ini:
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
Untuk memulai mencatat Makro maka pada menu Tools, sorot Macro kemudian sorot
Record New Macros lalu klik kiri tetikus (mouse),
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:
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
BelajarVBApadaMSExcel2003/2007
BelajarVBApadaMSExcel2003/2007
1. PENGGUNAAN DIM
Deklarasi variabel Boolean:
Dim I As Integer
Dim i, j As Integer
Dim R As Single
Dim a, b, c As Single
Dim D As Double
Dim x, y As Double
BelajarVBApadaMSExcel2003/2007
1. SINTAKS <FOR...NEXT>
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.
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.
BelajarVBApadaMSExcel2003/2007
BelajarVBApadaMSExcel2003/2007
2. SINTAKS <DO...WHILE>
Selain pernyataan <For...Next>, dikenal pula pernyataan bersangkar berupa <Do...While> 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.
BelajarVBApadaMSExcel2003/2007
BelajarVBApadaMSExcel2003/2007
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.
DoWhileActiveCell<>""'Loopsuntiltheactivecellisblank.
'The"&"musthaveaspaceonbothsidesoritwillbe
'treatedasavariabletypeoflonginteger.
ActiveCell.Offset(0,1).FormulaR1C1=_
ActiveCell.Offset(0,1)&""&ActiveCell.Offset(0,0)
ActiveCell.Offset(1,0).Select
Loop
End 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
8.
9.
1.
2.
3.
On the Insert menu, click Module to insert a module. Type the macro in the module's code
window.
4.
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.
9.
BelajarVBApadaMSExcel2003/2007
2.
3.
Klik menu Insert, kemudian klik Module untuk menyisipkan modul. Ketik makro dalam
jendela kode modul.
4.
5.
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.
2.
3.
On the Insert menu, click Module to insert a module. Type the macro in the module's code
window.
4.
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
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
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
Sub sekarang( )
Range (A1)= Now
End Sub
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
Sub tebal_merah( )
Selection.Font.Bold = True
Selection.Font.ColorIndex = 3
End Sub
BelajarVBApadaMSExcel2003/2007
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
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
Application.Goto Reference:=A1
atau
Range(A1).Select
BelajarVBApadaMSExcel2003/2007
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
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