Berikut ini adalah beberapa kumpulan script vba yang saya bersumber dari berbagai sumber, semoga dapat bermanfaat bagi saya khususnya dan bagi para pembaca pada umumnya.
Sumber Pertama : https://www.zaenalikhsan.com/2019/08/kumpulan-script-visual-basic-vb.html
Kumpulan Script Visual Basic ( VB ) Microsoft Excel
Kita perlu mempelajari Visual Basic ( VB ) yang ada di Microsoft Excel. Karena Script ini jika kita buat akan memudahkan orang bekerja jika aplikasi sudah jadi. Bagi orang yang ingin belajar bahasa pemograman Visual Basic memang dari Microsoft Excel sebagai dasar belajarnya karena mudah dipahami. Selamat mempelajari materi yang saya tulis ini semoga bermanfaat.
Coding VBA (Macro) Excel Menampikan Dokumen Di Layar Monitor
Sub PrintPreview()
Worksheets("Sheet1").PrintPreview
End Sub
Sheet1 disesuaikan nama sheetnya. Misal nama sheet diganti informatika ya di script disesuaikan
Coding VBA (Macro) Excel Menyimpan File Yang Baru Dibuat
Sub Save()
ActiveWorkbook.Save
End Sub
Coding VBA (Macro) Excel Keluar File
Sub Quit()
Application.Quit
End Sub
Coding VBA (Macro) Excel Menyisipkan Gambar Di DokumenSub insertpic()Dim FilestoOpenFilestoOpen = Application.GetOpenFilename("Picture File (*.jpg), *.jpg,(*.png), *.png", , "Insert Picture", , False)ActiveSheet.Pictures.Insert (OpenFilestoOpen)End Sub
Coding VBA (Macro) Excel Backup File
Sub FileBackUp()
ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _
"" & Format(Date, "mm-dd-yy") & " " & _
ThisWorkbook.name
End Sub
Coding VBA (Macro) Menutup Semua File Kecuali yang Aktif
Sub CloseAllWorkbooks()
Dim wbs As Workbook
For Each wbs In Workbooks
wbs.Close SaveChanges:=True
Next wbs
End Sub
Coding VBA (Macro) Menyembunyikan Worksheet
Sub HideWorksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> ThisWorkbook.ActiveSheet.Name Then
ws.Visible = xlSheetHidden
End If
Next ws
End Sub
Coding VBA (Macro) Menampilkan Semua Worksheet yang Tersembunyi
Sub UnhideAllWorksheet()
im ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
End Sub
Coding VBA (Macro) Menghapus Semua Worksheet
Sub DeleteWorksheets()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> ThisWorkbook.ActiveSheet.name Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
Coding VBA (Macro) Mengcopy Sheet Aktif kedalam Workbook Baru
Sub CopyWorksheetToNewWorkbook()
ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
End Sub
Coding VBA (Macro) Proteksi Semua Worksheet
Sub ProtectAllWorskeets()
Dim ws As Worksheet
Dim ps As String
ps = InputBox("Enter a Password.", vbOKCancel)
For Each ws In ActiveWorkbook.Worksheets
ws.Protect Password:=ps
Next ws
End Sub
Coding VBA (Macro) Mengkonversi Rumus kedalam Format Value
Sub ConvertToValues()
Dim MyRange As Range
Dim MyCell As Range
Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", vbYesNoCancel, "Alert")
Case Is = vbYes
ThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
Set MyRange = Selection
For Each MyCell In MyRange
If MyCell.HasFormula Then
MyCell.Formula = MyCell.Value
End If
Next MyCell
End Sub
Coding VBA (Macro) Menghapus Spasi
Sub RemoveSpaces()
Dim myRange As Range
Dim myCell As Range
Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", _
vbYesNoCancel, "Alert")
Case Is = vbYesThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
Set myRange = Selection
For Each myCell In myRange
If Not IsEmpty(myCell) Then
myCell = Trim(myCell)
End If
Next myCell
End Sub
Coding VBA (Macro) Memberi Tanda Data yang Dianggap Ganda (Duplikat)
Sub HighlightDuplicateValues()
Dim myRange As Range
Dim myCell As Range
Set myRange = Selection
For Each myCell In myRange
If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then
myCell.Interior.ColorIndex = 36
End If
Next myCell
End Sub
Coding VBA (Macro) Mengimpor File Excel Ke PDF
Sub SaveAsPDF()
Selection.ExportAsFixedFormat Type:=xlTypePDF, OpenAfterPublish:=True
End Sub
Coding VBA (Macro) Menghapus Karakter dari String
Public Function removeFirstC(rng As String, cnt As Long)
removeFirstC = Right(rng, Len(rng) - cnt)
End Function
Coding VBA (Macro) Menyimpan Range kedalam Bentuk Gambar
Sub PasteAsPicture()
Application.CutCopyMode = False
Selection.Copy
ActiveSheet.Pictures.Paste.Select
End Sub
Coding VBA (Macro) Cara Memberikan Tanda pada 10 Besar
Sub TopTen()
Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1)
.TopBottom = xlTop10Top
.Rank = 10
.Percent = False
End With
With Selection.FormatConditions(1).Font
.Color = -16752384
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13561798
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Coding VBA (Macro) Menambahkan Nomor Seri (Serial Number)
Sub AddSerialNumbers()
Dim i As Integer
On Error GoTo Last
i = InputBox("Enter Value", "Enter Serial Numbers")
For i = 1 To i
ActiveCell.Value = i
ActiveCell.Offset(1, 0).Activate
Next i
Last:
Exit Sub
End Sub
Coding VBA (Macro) Protek dan Unprotect Worksheet
Sub ProtectWS()
ActiveSheet.Protect "mypassword", True, True
End Sub
Sub UnprotectWS()
ActiveSheet.Unprotect "mypassword"
End Sub
Coding VBA (Macro) Merubah Tulisan Menjadi Huruf Besar
Sub ConvertUpperCase()
Dim rng As Range
For Each rng In Selection
rng = UCase(rng)
Next rng
End Sub
Coding VBA (Macro)Merubah Tulisan Menjadi Hurup Kecil
Sub ConvertLowerCase()
Dim rng As Range
For Each rng In Selection
rng = LCase(rng)
Next rng
End Sub
Coding VBA (Macro) Menyesuaikan Kolom dan Baris Sesuai Ukuran atau Lebar Text
Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
Sub AutoFitRows()
Cells.Select
Cells.EntireRow.AutoFit
End Sub
Coding VBA (Macro) Mengurutkan Nama Worksheet
Sub SortWorksheets()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
Coding VBA (Macro) Membuat text to Speak
Sub Speak()
Selection.Speak
End Sub
Coding VBA (Macro) Menutup Pesan Otomatis
Sub auto_close()
MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.com"
End Sub
Coding VBA (Macro)Konversi Format Tanggal ke Text
Sub date2day()
Dim tempCell As Range
Selection.Value = Selection.Value
For Each tempCell In Selection
If IsDate(tempCell) = True Then
With tempCell
.Value = Day(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
Coding VBA (Macro) Konversi Tanggal Menjadi Tahun
Sub date2year()
Dim tempCell As Range
Selection.Value = Selection.Value
For Each tempCell In Selection
If IsDate(tempCell) = True Then
With tempCell
.Value = Year(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
Coding VBA (Macro) Membuat Header dan Footer
Sub customHeader()
Dim myText As String
myText = InputBox("Enter your text here", "Enter Text")
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = myText
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub
Coding VBA (Macro) Menghapus Karakter
Sub removeChar()
Dim Rng As Range
Dim rc As String
rc = InputBox("Character(s) to Replace", "Enter Value")
For Each Rng In Selection
Selection.Replace What:=rc, Replacement:=""
Next
End Sub
Coding VBA (Macro) Menghapus Desimal
Sub removeDecimals()
Dim lnumber As Double
Dim lResult As Long
Dim rng As Range
For Each rng In Selection
rng.Value= Int(rng)
rng.NumberFormat= "0"
Next rng
End Sub
Coding VBA (Macro) Mengunci /Proteksi Cell yang ada Formulanya
Sub lockCellsWithFormulas()
With ActiveSheet
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
End Sub
Coding VBA (Macro) Menampilkan tulisan A-Z dalam sekejap
Sub addcAlphabets()
Dim i As Integer
For i= 65 To 90
ActiveCell.Value= Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Sub addsAlphabets()
Dim i As Integer
For i= 97 To 122
ActiveCell.Value= Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Coding VBA (Macro) Menghapus Cell Kosong
Sub deleteBlankWorksheets()
Dim Ws As Worksheet
On Error Resume Next
Application.ScreenUpdating= False
Application.DisplayAlerts= False
For Each Ws In Application.Worksheets
If Application.WorksheetFunction.CountA(Ws.UsedRange) = 0 Then
Ws.Delete
End If
Next
Application.ScreenUpdating= True
Application.DisplayAlerts= True
End Sub
Coding VBA (Macro) Memberikan Tanda pada Data yang Dianggap Unik
Sub highlightUniqueValues()
Dim rng As Range
Set rng = Selection
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub
sumber kedua : https://qdoc.tips/kumpulan-kode-vba-pdf-free.html
Kumpulan Kumpulan Kode VBA Excel Dasar Yang Yang Wajib Wajib Dipelajari Dipelajari | 300 Rumu...
http://www http://www.exc .excel-id. el-id.com/2 com/2015/09 015/09/kump /kumpulan-k ulan-kode-vb ode-vba-ex a-excel-d cel-dasarasar-yan.. yan....
http://www.excel-id.com/201 http://www.excel-id.com/2015/09/kumpu 5/09/kumpulan-kode-vba lan-kode-vba-excel-dasar-yang -excel-dasar-yang.html .html
VBA merupakan Visual Basic of Application dimana VBA ini sangat membantu sekali dalam mengolah data Excel. Jika Anda mahir Excel maka akan sangat hebat apabila dikolaborasikan dengan kode-kode VBA. Jika Anda baru belajar tentang kode-kode VBA berikut contoh dasar kode VBA excel bagi pemula.
'==Kode VBA Memilih 2 baris ke bawah dan 2 kolom ke kanan:
ActiveCell.Offset(3, 2).Select
'==Kode VBA Pilih dari sel aktif ke baris terakhir dari daftar: '==Kode VBA Pilih dari sel saat ini untuk kolom terakhir dari Range(Selection, Selection.End(xlDown)).Select
daftar: '==Kode Range(Selection, Sel ection.End(xlToRight)).Select ection.End(xlToRight)).Select
VBA Pilih sel terakhir dari worksheet:
Selection.SpecialCells(xlLastCell).Select
'==Kode VBA Nilai rumus Paste, bukan rumus: '==Kode VBA Paste ke dalam sel dan memindahkan memindahkan isi aslinya ke sel berikutnya: Range("A3").Copy Range("D26").PasteSpecial Paste:=xlValues
Selection.Insert Shi ft:=xlToRight ft:=xlToRight
'==Kode VBA Menyembuntikan Kolom: '==Kode VBA Menyisipkan Kolom: '==Kode VBA Menghapus Kolom:
Selection.EntireColumn.Hidden = True
'==Kode VBA Menyisipkan baris baru
Columns("N:N").Insert Columns("B:E").EntireColumn.Delete
di cell saat ini: '==Kode Selection.EntireRow.Insert
VBA
menghapus baris baru di cell saat ini: '==Kode VBA Mengatur lebar kolom: '==Kode VBA Mengatur tinggi baris
Selection.EntireRow.Delete
'==Kode VBA Mengatur tinggi baris
Selection.EntireColumn.ColumnWidth = 10 Selection.RowHeight = 26.25
dengan ukuran isi:
Selection.Rows.AutoFit
'==Kode VBA Wrap Teks '==Kode VBA Mengahpus warna '==Kode VBA mengatur ukuran huruf
Selection.WrapText = False
'==Kode VBA mengatur format tanggal dan
Selection.Interior.ColorIndex = xlNone Selection.Font.Size = 8
waktu '==Kode VBA mengatur angka desimal/pecahan
1 f3
6/25/17 3 01 PM
Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumu...
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yan...
Selection.Font.Size = 8
'==Kode VBA mengatur angka desimal/pecahan '==Kode VBA perataan tengah Selection.NumberFormat = "mm-dd-yyyy hh:mm AM/PM"
'==Kode
Selection.NumberFormat = "#,##0" Selection.HorizontalAlignment = xlLeft
VBA rata bawah
'==Indented text: '==Kode VBA Hapus isi tapi tidak format:
Selection.VerticalAlignment = xlBottom
'==Kode VBA Hapus isi dan format:
Selection.IndentLevel = 3 Selection.ClearContents
Selection.Clear
'==Kode VBA Menyembunyikan aktivitas sementara makro berjalan: '==Kode VBA Matikan lansiran otomatis: '==Kode VBA untuk Freeze panes:
Application.ScreenUpdating = False
'==Kode VBA Tampilkan berjalan
Application.DisplayAlerts = False ActiveWindow.FreezePanes = True
Dim strTime1 as String, strTime2 as String
makro berapa lama:
'==Kode VBA menamai range
strTime1 = Format(Now(), "mm-dd-yyyy hh:MM:ss")
'==Kode VBA
[put other macro code here]
ActiveWorkbook.Names.Add Name:="Groups", RefersTo:=Selection
menuju ke alamat range
strTime2 = Format(Now(), "mm-dd-yyyy hh:MM:ss")
'==kode VBA
MsgBox "Elapsed Time = " & DateDiff("n", strTime1, strTime2)
menghapus nama range workbook aktif Range("Groups").Select Dim n as Object For Each n In ActiveWorkbook.Names
'==Kode VBA
n.Delete
menyisimpan
Next
nama lokasi file '==kode VBA untuk Insert path/file kedalam footer ActiveCell.Value = ActiveWorkbook.FullName
ActiveSheet.PageSetup.CenterFooter = ActiveWorkbook.FullName
'===Kode VBA Menghapus item yang tidak terpakai di tabel pivot ketika data telah berubah:
Dim pt As PivotTable, ws As Worksheet For Each ws In ActiveWorkbook.Worksheets For Each pt In ws.PivotTables
'==Kode VBA Menambahkan tanggal untuk judul setiap worksheet:
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
Semoga bermanfaat. dan
Next pt
Dim sht As Worksheet
Next ws
For Each sht In ActiveWorkbook.Worksheets sht.Select
untuk melihat contoh penggunaan kode VBA lebih lengkap silakan lihat
Range("A1").Value = Range("A1").Value & " through " & strDate
contoh Pembuatan Input
Next sht
Data dengan VBA UPDATE : Koleksi Kode
VBA untuk Belajar Macro Dasar 12/12/2015
Sub CopyRange( ) Range (“A1:B10”).Copy Destination:=Range(“D1:E10”) End Sub
Sub AlamatCell( ) baris = ActiveCell.Row
2 f3
kolom = ActiveCell.Column
Sub MerubahFont( )
6/25/17 3 01 PM
Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumu...
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yan...
End Sub baris = ActiveCell.Row kolom = ActiveCell.Column
Sub MerubahFont( )
Msgbox baris & “,” & kolom
Selection.Font.Bold = True ’ untuk menebalkan huruf
End Sub
Selection.Font.ColorIndex = 3 ’ untuk mewarna merah End Sub
Private Sub UserForm_Initialize() With UserForm1.ListBox1 .RowSource = "ListData"
atau bisa juga gunakan
Sheets(1).Select
.ColumnCount = 5 Sheets1.Select .ColumnWidths = "37,95,60,60,50"
Contoh Lain : Sheets("Sheet1").Select
End With End Sub
Sheet1.Visible = xlSheetVeryHidden
InputBox(“Silakan Masukan Nama Anda”)
Range(“A1”).Select ’ Pilih range Selection.EntireRow.Insert ’ sisipkan baris diatas range A1 ActiveWorkbook.SaveAs Filename:=”D:\LatihanVBA.xls”
Private Sub TextBox1_Change() TextBox1.Value = Format(TextBox1.Value, "dd/mm/yyyy") Dim i As Long
End Sub
Dim j As Long
Contohnya kita mempunya data ListBox2.ColumnCount = ListBox1.ColumnCount For i = 0 To ListBox1.ListCount - 1 If ListBox1.Selected(i) Then With ListBox2
.AddItem For j = 0 To .ColumnCount - 1 .List(.ListCount - 1, j) = ListBox1.List(i, j) Next j End With
pada listbox dengan 5 kolom dan masing-masing data akan ditampilkan pada textbox maka kita harus mempunya textbox sebanyak 5 kolom juga dan berikut coding VBA nya Oke, segitu ajah dulu koleksi coding VBA lengkap dan akan terus dilengkapi contoh-contoh coding dasar VBA. Tunggu ajah ya update nya...
End If Next i
Private Sub ListBox1_AfterUpdate() Me.TextBox1.Value = Me.ListBox1.Column(0) Me.TextBox2.Value = Me.ListBox1.Column(1) Me.TextBox3.Value = Me.ListBox1.Column(2) Me.TextBox4.Value = Me.ListBox1.Column(3) Me.TextBox5.Value = Me.ListBox1.Column(4) End Sub
Sumber Ketiga : https://pdfcoffee.com/qdownload/kumpulan-kode-vba-excel-dasar-yang-wajib-dipelajari-300-rumus-excelpdf-pdf-free.html
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 1/6
VBA merupakan Visual Basic of Application dimana VBA ini sangat membantu sekali dalam
mengolah data Excel. Jika Anda mahir Excel maka akan sangat hebat apabila dikolaborasikan
dengan kode-kode VBA. Jika Anda baru belajar tentang kode-kode VBA berikut contoh dasar kode
VBA excel bagi pemula.
'==Kode VBA Memilih 2 baris ke bawah dan 2 kolom ke kanan:
'==Kode VBA Pilih dari sel aktif ke baris terakhir
dari daftar:
'==Kode VBA Pilih dari sel saat ini untuk kolom terakhir dari daftar:
'==Kode VBA Pilih sel terakhir dari worksheet:
'==Kode VBA Nilai rumus Paste, bukan rumus:
'==Kode VBA Paste ke dalam sel dan
memindahkan isi aslinya ke sel berikutnya:
'==Kode VBA Menyembuntikan Kolom:
'==Kode VBA Menyisipkan Kolom:
'==Kode VBA Menghapus Kolom:
'==Kode VBA Menyisipkan baris baru di cell saat
ini:
'==Kode VBA menghapus baris baru di cell saat ini:
'==Kode VBA Mengatur lebar kolom:
Selecting
ActiveCell.Offset(3, 2).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlLastCell).Select
Pasting
Range("A3").Copy
Range("D26").PasteSpecial Paste:=xlValues Selection.Insert Shift:=xlToRight
Columns and Rows
Selection.EntireColumn.Hidden = True
Columns("N:N").Insert
Columns("B:E").EntireColumn.Delete
Selection.EntireRow.Insert
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 2/6
'==Kode VBA Mengatur tinggi baris
'==Kode VBA Mengatur tinggi baris dengan
ukuran isi:
'==Kode VBA Wrap Teks
'==Kode VBA Mengahpus warna
'==Kode VBA mengatur ukuran huruf
'==Kode VBA mengatur format tanggal dan
waktu
'==Kode VBA mengatur angka desimal/pecahan
'==Kode VBA perataan tengah
'==Kode VBA rata bawah
'==Indented text:
'==Kode VBA Hapus isi tapi tidak format:
'==Kode VBA Hapus isi dan format:
Selection.EntireRow.Delete Selection.EntireColumn.ColumnWidth = 10
Selection.RowHeight = 26.25
Selection.Rows.AutoFit
Cell Formatting
Selection.WrapText = False
Selection.Interior.ColorIndex = xlNone
Selection.Font.Size = 8
Selection.NumberFormat = "mm-dd-yyyy hh:mm
AM/PM"
Selection.NumberFormat = "#,##0"
Selection.HorizontalAlignment = xlLeft
Selection.VerticalAlignment = xlBottom
Selection.IndentLevel = 3
Selection.ClearContents
Selection.Clear
Display
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 3/6
'==Kode VBA Menyembunyikan aktivitas sementara makro berjalan:
'==Kode VBA Matik an lansiran otomatis:
'==Kode VBA untuk Freeze panes:
'==Kode VBA Tampilkan berjalan makro berapa
lama:
'==Kode VBA menamai range
'==Kode VBA menuju ke alamat range
'==kode VBA menghapus nama range workbook
aktif
'==Kode VBA menyisimpan nama lokasi file
'==kode VBA untuk Insert path/file kedalam footer
'===Kode VBA Menghapus item yang tidak
terpakai di tabel pivot ketika data telah berubah:
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.FreezePanes = True
Dim strTime1 as String, strTime2 as String
strTime1 = Format(Now(), "mm-dd-yyyy
hh:MM:ss")
[put other macro code here]
strTime2 = Format(Now(), "mm-dd-yyyy
hh:MM:ss")
MsgBox "Elapsed Time = " & DateDiff("n",
strTime1, strTime2)
Range Names
ActiveWorkbook.Names.Add Name:="Groups",
RefersTo:=Selection
Range("Groups").Select
Dim n as Object
For Each n In ActiveWorkbook.Names
n.Delete
Next
Path/File Name
ActiveCell.Value = ActiveWorkbook.FullName
ActiveSheet.PageSetup.CenterFooter =
ActiveWorkbook.FullName
Pivot Tables
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 4/6
'==Kode VBA Menambahkan tanggal untuk judul
setiap worksheet:
Semoga bermanfaat. dan untuk melihat contoh penggunaan kode VBA lebih lengkap silakan lihat
contoh
Dim pt As PivotTable, ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
pt.PivotCache.MissingItemsLimit =
xlMissingItemsNone
Next pt
Next ws
Worksheets
Dim sht As Worksheet
For Each sht In ActiveWorkbook.Worksheets
sht.Select
Range("A1").Value = Range("A1").Value & "
through " & strDate
Next sht
Pembuatan Input Data dengan VBA
UPDATE : Koleksi Kode VBA untuk Belajar Macro Dasar
12/12/2015
Coding untuk Copy Paste Range
Sub CopyRange( )
Range (“A1:B10”).Copy
Destination:=Range(“D1:E10”)
End Sub
Kode Menampilkan Posisi Cell yang Aktif
Sub AlamatCell( )
baris = ActiveCell.Row
kolom = ActiveCell.Column
Msgbox baris & “,” & kolom
End Sub
Kode VBA untuk format tebal huruf dan pewarnaan
Sub MerubahFont( )
Selection.Font.Bold = True ' untuk menebalkan huruf
Selection.Font.ColorIndex = 3 ' untuk mewarna
merah
End Sub
Coding VBA merubah Properties Listbox
(Jumlah kolom, Rowsource, Jumlah kolom
dan ukuran kolom.
Private Sub UserForm_Initialize()
With UserForm1.ListBox1
.RowSource = "ListData"
.ColumnCount = 5
.ColumnWidths = "37,95,60,60,50"
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 5/6
atau bisa juga gunakan
End With
End Sub
Coding Menuju Sheet tertentu
Sheets(1).Select
Sheets1.Select
Contoh Lain : Sheets("Sheet1").Select
Coding VBA menyembunyikan Sheet1
Sheet1.Visible = xlSheetVeryHidden
Coding VBA menampilkan Input Box
InputBox(“Silakan Masukan Nama Anda”)
Contoh Coding Menyisipkan atau
menambah baris diatas range tertentu
Range(“A1”).Select ' Pilih range
Selection.EntireRow.Insert ' sisipkan baris diatas
range A1
Coding VBA menyimpan nama file
ActiveWorkbook.SaveAs
Filename:=”D:\LatihanVBA.xls”
Contoh Coding Format Tanggal pada
Textbox
Private Sub TextBox1_Change()
TextBox1.Value = Format(TextBox1.Value,
"dd/mm/yyyy")
End Sub
26/12/2018 Kumpulan Kode VBA Excel Dasar Yang Wajib Dipelajari | 300 Rumus Excel
http://www.excel-id.com/2015/09/kumpulan-kode-vba-excel-dasar-yang.html 6/6
Contohnya kita mempunya data pada listbox
dengan 5 kolom dan masing-masing data akan
ditampilkan pada textbox maka kita harus
mempunya textbox sebanyak 5 kolom juga dan
berikut coding VBA nya
Oke, segitu ajah dulu koleksi coding VBA
lengkap dan akan terus dilengkapi contoh-contoh
coding dasar VBA. Tunggu ajah ya update nya..
Coding Copy Listbox1 ke Listbox 2
Dim i As Long
Dim j As Long
ListBox2.ColumnCount = ListBox1.ColumnCount
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
With ListBox2
.AddItem
For j = 0 To .ColumnCount - 1
.List(.ListCount - 1, j) = ListBox1.List(i,
j)
Next j
End With
End If
Next i
Coding VBA menampilkan Listbox ke
Textbox
Private Sub ListBox1_AfterUpdate()
Me.TextBox1.Value = Me.ListBox1.Column(0)
Me.TextBox2.Value = Me.ListBox1.Column(1)
Me.TextBox3.Value = Me.ListBox1.Column(2)
Me.TextBox4.Value = Me.ListBox1.Column(3)
Me.TextBox5.Value = Me.ListBox1.Column(4)
End Sub
Sumber Keempat : https://b-excel.blogspot.com/2013/07/koleksi-macro-dasar-excel.html
Activate | Sub Worksheet_Activate() MsgBox "Hello" End Sub |
Active Cell, Position | myRow = ActiveCell.Row myCol = ActiveCell.Column MsgBox myRow & "," & myCol |
Active Cell, Selection to far left | Selection.End(xlToLeft).Select
OR
Range("A" & ActiveCell.Row).Select |
Active Cell in top left of screen | With ActiveWindow .ScrollColumn = ActiveCell.Column .ScrollRow = ActiveCell.Row End With |
Active Cell, Value | MsgBox ActiveCell.Value |
Auto Run | Sub Auto_Open() MsgBox "Hello" End Sub |
Auto Run(2) | Sub Workbook_Open() MsgBox "Hello" End Sub |
Auto Save | This workbook: ' = Autorun Sub Workbook_Open() Call SaveMe End Sub
In Module: Sub SaveMe() ThisWorkbook.Save Application.OnTime Now + Timeserial(0,15,0),"SaveMe" ' Timeserial=(h,m,s) End Sub |
Available Row (next) | Range("a65536").End(xlUp).Offset(1, 0).Select |
Call - Running a subroutine | Call Macro2 'This calls for Macro2 to run within your Macro |
Case Title | Dim cell As Range For Each cell In Selection.Cells If cell.HasFormula = False Then cell = Application.Proper(cell) End If Next |
Case Upper / Lower | Dim cell As Range For Each cell In Selection.Cells If cell.HasFormula = False Then cell = UCase(cell) End If Next |
Column Letters | Dim MyColumn As String, Here As String Here = ActiveCell.Address MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2) MsgBox MyColumn |
Counting Rows & Columns | myRows = Selection.Rows.Count myColumns = Selection.Columns.Count MsgBox "Rows = " & myRows & vbCrLf & "Colums = " & myColumns |
Carriage Return | MsgBox "Line 1" & vbCrLf & "Line 2" |
Copy Range (1) | Sheet1.Range("A1:C1").Copy Destination:=Sheet2.Range("A1") |
Copy Range (2) | Range("A1:B1").Copy Range("A2").PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False |
Counter | Range("A1") = Range("A1") + 1
OR
myCount = Range("a1") + 1 Range("a1") = myCount |
Current Date | Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Range("A1") = Now End Sub |
Delete Empty Rows | firstRow = Selection.Row lastRow = Selection.Row + Selection.Rows.Count For rownumber = lastRow To firstRow Step -1 If Application.WorksheetFunction.CountA(Rows(rownumber)) = 0 _ Then Rows(rownumber).Delete Next rownumber |
Error Trapping | On Error Resume Next
OR
Sub Name() On Error Goto ErrorHandler1 ... more lines of code Exit Sub ErrorHandler1: ... code specifying action on error End Sub |
File Name & Path | Range("A1") = Application.ActiveWorkbook.FullName |
For, Next Loop | |
Goto (Code) | |
Input Box | Dim MyInput MyInput = InputBox("Enter something") Range("A1") = MyInput |
If, Then Statement | If Range("B1") > 10 Then Range("B2") = 10 ElseIf Range("B2") > 5 Then Range("B2") = 5 Else Range("B2") = 1 End If |
Joining Text | myCol = Selection.Columns.Count - 1 n = 0 For n = 0 To Selection.Rows.Count - 1 For i = 1 To myCol ActiveCell.Offset(n, 0) = ActiveCell.Offset(n, 0) & ActiveCell.Offset(n, i) ActiveCell.Offset(n, i) = "" Next i Next n |
Message Box | MsgBox "Created by: Your Name here" MsgBox "Different Icon", vbInformation MsgBox "Different Icon And Title", vbExclamation, "Your warning message" |
Modeless Forms | UserForm.show vbModeless |
Moving the Cursor | ActiveCell.Offset(1, 0).Select |
Protecting / Unprotecting a sheet | 'Protect Dim Password Password = "xxxx" ActiveSheet.Protect Password, True, True, True
'Unprotect Password = "xxxx" ActiveSheet.Unprotect Password |
Random numbers | MyNumber = Int((10 - 1 + 1) * Rnd + 1) Range("A1") = MyNumber |
Rounding Numbers | ActiveCell = Application.round(ActiveCell, 2) |
Saving your Workbook | ActiveWorkbook.Save |
ScreenUpdating | Application.ScreenUpdating = False / True |
Select Case statement | Select Case Range("A1").Value Case 100, 150 ' = 100 OR 150 Range("B1").Value = Range("A1").Value Case 200 To 300, 400 To 500 ' = Between 200 and 300 OR between 400 and 500 Range("B2").Value = Range("A1").Value Case Else Range("B1").Value = 0 End Select |
Select Data Range | Dim myLastRow As Long Dim myLastColumn As Long Range("A1").Select On Error Resume Next myLastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row myLastColumn = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column myRange = "a1:" & Cells(myLastRow, myLastColumn).Address Range(myRange).Select |
Sheets Hiding | Sheet1.Visible = xlSheetVeryHidden |
Text Edit | MsgBox Left("abcd", 2) 'Displays 2 characters from Left MsgBox Right("abcd", 2) 'Displays 2 characters from Right MsgBox Len("abcd") 'Displays number of characters (Including space) |
Timer | Application.Wait Now + TimeValue("00:00:05") MsgBox ("This was a 5 second delay") |
Time last save | MsgBox Excel.Application.ThisWorkbook.BuiltinDocumentProperties("Last Save Time") |
vbYesNo | YesNo = MsgBox("This macro will ... Do you want to continue?", vbYesNo + vbCritical, "Caution") Select Case YesNo Case vbYes 'Insert your "Yes" code here. Case vbNo 'Insert your "No" code here. End Select
|