0% found this document useful (0 votes)
7 views

VBA vỡ lòng

The document serves as an introductory guide to VBA (Visual Basic for Applications), detailing various commands and syntax for manipulating sheets, cells, ranges, columns, rows, and workbooks. It also includes sections on error handling, file management, settings, arrays, collections, and dictionaries, along with a brief introduction to UniTrain Consulting and Training Co., Ltd. and their courses on Excel automation, Power Query, and dashboard reporting.

Uploaded by

donglac98bn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

VBA vỡ lòng

The document serves as an introductory guide to VBA (Visual Basic for Applications), detailing various commands and syntax for manipulating sheets, cells, ranges, columns, rows, and workbooks. It also includes sections on error handling, file management, settings, arrays, collections, and dictionaries, along with a brief introduction to UniTrain Consulting and Training Co., Ltd. and their courses on Excel automation, Power Query, and dashboard reporting.

Uploaded by

donglac98bn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

VBA vỡ lòng

CÁC LỆNH VÀ CÚ PHÁP


VBA PHỔ BIẾN

UniTrain Consulting and Training Co., Ltd.


Tầng 4, tòa nhà Thiên Sơn
5 Nguyễn Gia Thiều, P.6, Q.3, TP. HCM
Hotline hỗ trợ tư vấn: 0901 175 625
[email protected]
www.unitrain.edu.vn
SHEETS
Description VBA Code
Activate by Tab Name Sheets(“Input”).Activate

Activate by VBA Code Name Sheet1.Activate

Activate by Index Position Sheets(1).Activate

Next Sheet ActiveSheet.Next.Activate

Get ActiveSheet MsgBox ActiveSheet.Name

Select Sheet Sheets(“Input”).Select

Set to Variable Dim ws as Worksheet


Set ws = ActiveSheet
Name / Rename ActiveSheet.Name = “NewName”

Add Sheet Sheets.Add

Add Sheet and Name Sheets.Add.Name = “NewSheet”

Add Sheet to Variable Dim ws As Worksheet Set ws = Sheets.Add

Copy Sheet Sheets(“Sheet1”).Copy Before:=Sheets(“Sheet2”)

Hide Sheet Sheets(“Sheet1”).visible = False or


Sheets(“Sheet1”).visible = xlSheetHidden
Unhide Sheet Sheets(“Sheet1”).Visible = True or
Sheets(“Sheet1”).Visible = xlSheetVisible
Very Hide Sheet Sheets(“Sheet1”).Visible = xlSheetVeryHidden

Delete Sheet Sheets(“Sheet1”).Delete

Clear Sheet Sheets(“Sheet1”).Cells.Clear

Unprotect (No Password) Sheets(“Sheet1”).Unprotect

Unprotect (Password) Sheets(“Sheet1”).Unprotect “Password”

Protect (No Password) Sheets(“Sheet1”).Protect

Protect (Password) Sheets(“Sheet1”).Protect “Password”

Protect but Allow VBA Access Sheets(“Sheet1”).Protect UserInterfaceOnly:=True

Hotline: 0901 175 625


www.unitrain.edu.vn
CELLS & RANGES

Description VBA Code


Range(“B3”).Activate
Activate Cell
Cells(3,2).Activate
Range(“a1:a3”).Select
Range(Range(“a1”), Range(“a3”)).Select
Select Range
Range(Cells(1, 1), Cells(3, 1)).Select
Resize Range(“B3”).Resize(2, 2).Select

Offset Range(“B3”).Offset(2, 2).Select

Copy Range(“A1:B3”).Copy Range(“D1”)

Cut Range(“A1:B3”).Cut Range(“D1”)


Range(“A1:B3”).Delete
Delete
Range(“A1:B3”).Delete shift:=xlShiftToLeft
Range(“A1:A3”).Clear
Clear
Range(“A1:A3”).ClearContents Range(“A1:A3”).ClearFormat
Count Range(“A1:A3”).Count
Dim rng as Range
Set to Variable
Set rng = Range(“A1”)
Range(“A1:A3”).Merge
Merge/UnMerge
Range(“A1:A3”).UnMerge
Dim cell As Range

For Each cell In Range(“A1:C3”)


Loop Through Cells
MsgBox cell.Value
Next cell

Hotline: 0901 175 625


www.unitrain.edu.vn
COLUMNS
Description VBA Code
Columns(1).Activate
Activate Columns(“a:a”).Activate
Range(“a1”).EntireColumn.Activate
Height / Width Range(“A1”).EntireColumn. ColumnWidth = 30

Delete Range(“A1”).EntireColumn.Delete

Count Range(“A1”).Columns.Count

Insert Range(“A1”).EntireColumn.Insert
dim lCol as long
Last lCol = Cells(1, Columns.Count).End
(xlToLeft).Column
Copy Range(“A:A”).Copy Range(“E:E”)
Range(“A:A”).Copy
Insert
Range(“E:E”).Insert

Hotline: 0901 175 625


www.unitrain.edu.vn
WORKBOOKS
Description VBA Code
Activate Workbooks(“Book1”).Activate

Activate First Opened Workbooks(1).Activate

Activate Last Opened Workbooks(Workbooks.Count).Activate

Get activate Workbook MsgBox ActiveWorkbook.Name

Get ThisWorkbook (containing


VBA Code) MsgBox ThisWorkbook.Name
Add Workbooks.Add

Add to Variable Dim wb As Workbook Set wb = Workbooks.Add

Open Workbooks.Open(“C:\example.xlsm”)

Dim wb As Workbook
Open to Variable Set wb = Workbooks.Open(“C:\example. xlsm”)
Workbooks(“Book1”).Close SaveChanges:=False
Close Workbooks(“Book1”).Close SaveChanges:=True
Save Workbooks(“Book1”).Save

Save As Workbooks(“Book1”).SaveAs strFileName

Protect/ Unprotect Workbooks(1).Protect “password” Workbooks(1).Unprotect


“password”
Set to Variable Dim wb as Workbook
Set wb = Workbooks(“Book1”)
Dim wb As Workbook
Loop Through All Workbook in
Workbooks For Each wb In Workbooks MsgBox wb.Name
Next wb
If Dir(“C:\Book1.xlsx”) = “” Then MsgBox “File does not
Check Exists exist.” EndIf
Copy Closed FileCopy “C:\file1.xlsx”,”C:\file2.xlsx”

Hotline: 0901 175 625


www.unitrain.edu.vn
ROWS
Description VBA Code
Rows(1).Activate
Rows(“1:1”).Activate
Activate
Range(“a1”).EntireRow.Activate
Height / Width Range(“A1”).EntireRow.RowHeight = 30

Delete Range(“A1”).EntireRow.Delete

Count Range(“A1”).Rows.Count

Insert Range(“A1”).EntireRow.Inser
dim lRow as long
lRow = Cells(Rows.Count, 1).End(xlUp).
Last
Row
Copy Range(“1:1”).Copy Range(“5:5”)
Range(“1:1”).Copy
Insert
Range(“5:5”).Insert

ERRORS
Description VBA Code
On Error – Stop code and display error On Error Goto 0

On Error – Skip error and continue running On Error Resume Next

On Error – Go to a line of code [Label] On Error Goto [Label]

Clears (Resets) Error On Error GoTo –1

Show Error number MsgBox Err.Number

Show Description of error MsgBox Err.Description

Function to gen- erate own error Err.Raise

Hotline: 0901 175 625


www.unitrain.edu.vn
FILES

Description VBA Code


Copy File FileCopy “C:\test\test_old.xlsx”, “C:\test\ test_new.xlsx”

Delete File Kill “C:\test\example.xlsx”

Make Folder MkDir “C:\test\”


Delete All Files From
Kill “C:\test\” & “*.*”
Folder
Kill “C:\test\” & “*.*”
Delete Folder
RmDir “C:\test\”
Current Directory strPath = CurDir()

ThisWorkbook Path strPath = ThisWorkbook.Path

strFile = Dir(“C:\test” & “\*”)


Do While Len(strFile) > 0
Loop Through All Debug.Print
Files in Folder strFile strFile = Dir
Loop

Hotline: 0901 175 625


www.unitrain.edu.vn
SETTINGS
Description VBA Code
Application.ScreenUpdating = False
Screen Updating
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Display Alerts
Application.DisplayAlerts = True
Application.EnableEvents = False
Events
Application.EnableEvents = True
Application.EnableCancelKey = xlDisabled
Enable Cancel Key
Application.EnableCancelKey = xlInterrupt
Text Compare – Ignore Case Option Compare Text

Require Variable Declaration Option Explicit


Application.Calculation = xlManual
Automatic Calcu- lations
Application.Calculation = xlAutomatic
Application.ErrorCheckingOptions.
BackgroundChecking = False
Background Error Checking Application.ErrorCheckingOptions.
BackgroundChecking = True
Application.DisplayFormulaBar = False
Display Formula Bar
Application.DisplayFormulaBar = True
ActiveWindow.FreezePanes = False
Freeze Panes
ActiveWindow.FreezePanes = True
Application.DisplayFullScreen = False
Full Screen View
Application.DisplayFullScreen = True
ActiveWindow.View = xlPageBreakPreview
PageBreak Preview
ActiveWindow.View = xlNormalView
Application.DisplayStatusBar = False
Display Status Bar
Application.DisplayStatusBar = True
Application.StatusBar = “I’m working Now!!!”
Status Bar Contents
Application.StatusBar = False
ActiveWindow.DisplayWorkbookTabs
= False
Display Work- book Tabs ActiveWindow.DisplayWorkbookTabs
= True
UserName Application.UserName = “UniTrain.vn”

App Caption Application.Caption = “UniTrain”

Zoom ActiveWindow.Zoom = 80

Hotline: 0901 175 625


www.unitrain.edu.vn
ARRAYS

Description VBA Code


Dim arr(1 To 3) As Variant
arr(1) = “one”
Create
arr(2) = “two”
arr(3) = “three”
Dim arr(1 To 3) As Variant
Dim cell As Range, i As Integer
i = LBound(arr)
Create From Excel For Each cell In Range(“A1:A3”)
i=i+1
arr(i) = cell.value
Next cell
Dim i as Long
Fori = LBound(arr) To UBound(arr)
Read All Items
MsgBox arr(i)
Next I
Erase Erase arr
Dim sName As String
Array to String
sName = Join(arr, “:”)
Increase Size ReDim Preserve arr(0 To 100)

Set Value arr(1) = 22

Hotline: 0901 175 625


www.unitrain.edu.vn
COLLECTIONS

Description VBA Code


Dim coll As New Collection
Create coll.Add “one”
coll.Add “two”
Dim coll As New Collection
Dim cell As Range
Create From Excel For Each cell In Range(“A1:A2”)
coll.Add cell.value
Next cell
Add Item coll.Add “Value”

Add Item Before coll.Add “Value”, Before:=1

Add Item After coll.Add “Value”, After:=1


Read Item MsgBox coll (1)

Count Items coll.Count


Dim item As Variant
For Each item In coll
Read All Items MsgBox item
Next item
Remove Item coll.Remove (1)

Remove All Items Set coll = New Collection

Hotline: 0901 175 625


www.unitrain.edu.vn
DICTIONARIES

Description VBA Code


Required Reference Tools > References > Microsoft Scripting Runtime
Dim dict As New Scripting.Dictionary
Create dict.Add “”
dict.Add “”
Dim dict As New Scripting.Dictionary
Dim cell As Range
Dim key As Integer
Create From Excel For Each cell In Range(“A1:A10”)
key = key + 1
dict.Add key, cell.value
Next cell
Add Item dict.Add “Key”, “Value”

Change Value dict(“Key”) = “Value”

Get Value MsgBox dict(“Key”)


If dict.Exists(“Key”) Then
MsgBox “Exists”
Check For Value
End If
Remove Item dict.Remove (“Key”)

Remove All Items dict.RemoveAll


Dim key As Variant
For Each key In dict.Keys
Loop Through Items MsgBox key, dict(key)
Next key
Count Items dict.Count

Make Key Case Sensitive dict.CompareMode = vbBinaryCompare

Make Key Case Insensitive dict.CompareMode = vbTextCompare

Hotline: 0901 175 625


www.unitrain.edu.vn
GIỚI THIỆU

Trung tâm
Tư vấn & Đào tạo
UniTrain
UniTrain là đơn vị cung cấp các dịch vụ tư vấn và đào tạo
chuyên nghiệp trong lĩnh vực kế toán, kiểm toán và tài
chính với đội ngũ giảng viên dày dặn kinh nghiệm quản lý
tại các công ty kiểm toán lớn (Big 4), các định chế tài chính
và tập đoàn đa quốc gia hàng đầu tại Việt Nam.

Sứ mệnh của công ty là truyền đạt và chuyển hóa các kiến


thức chuyên ngành thành giá trị thực tế cho các khách hàng
của mình, nhân viên của công ty, cũng như cho toàn thể nền
kinh tế Việt Nam trong giai đoạn hội nhập và phát triển.
Chúng tôi cam kết cung cấp cho khách hàng các dịch vụ đào
tạo chuyên ngành kế toán, kiểm toán, thuế và tài chính đã
được chuẩn hóa, chuyên nghiệp và nhất quán.

Mọi chi tiết xin liên hệ


UniTrain Consulting & Training Ltd., Co.
Tầng 4, Tòa nhà Thiên Sơn
5 Nguyễn Gia Thiều, P.6, Q.3, TP. HCM
Hotline 0901 175 625 – Tel: (028) 66 826 629
Email: [email protected]

www.unitrain.edu.vn Hotline: 0901 175 625


GIỚI THIỆU
Khóa học
𝐂𝐎𝐌𝐁𝐎 𝐄𝐗𝐂𝐄𝐋 𝐀𝐔𝐓𝐎𝐌𝐀𝐓𝐈𝐎𝐍
VBA
❑ Khả năng viết code cơ bản, đọc hiểu code phức tạp, áp dụng
tự động hóa vào công việc hàng ngày.
❑ Thiết kế các hệ thống tự động hóa cơ bản nhằm đáp ứng các
yêu cầu báo cáo hiệu quả, thông tin chính xác và kịp thời.
❑ Tự tạo phím tắt và các nút lệnh.
❑ Ứng dụng tự động hóa với dữ liệu lớn (big data) hoặc các
thao tác thủ công khi lập báo cáo hàng
ngày/tháng/quý/năm…

POWER QUERY
❑ Quy tắc tổ chức dữ liệu báo cáo trong Excel.
❑ Các chức năng thông dụng của Power Query.
❑ Chức năng phân tích dữ liệu bằng Pivot Table, Power Pivot.

DASHBOARD REPORTING
❑ Tạo Dashboard bằng các tính năng có sẵn của Excel.
❑ Trình bày Dashboard chuyên nghiệp và hiệu quả.

* Click tên khóa học để xem chi tiết

Hotline: 0901 175 625


www.unitrain.edu.vn

You might also like