Mô tả ví dụ: cho ma trận số nguyên có n hàng và m cột được lưu trong sheet "input", ma trận đó có những vị trí bị rỗng. Nhiệm vụ là tạo ra một sheet "output" chứa ma trận ở sheet "input" và điền vào những ô trống giá trị 0.
Ví dụ: input
Kết quả mong muốn: output
Có thể sử dụng các đối tượng Workbook và Worksheet để giải quyết bài toán này.
Nội dung chính
Lời giải
Tạo một button và assign macro như trong bài tạo một Macro trong Excel.
Tạo module có nội dung như sau:
Option Explicit
Public Const SHEET_INPUT = "input"
Public Const SHEET_OUTPUT = "output"
Sub ClickButton()
Call ViDu1
End Sub
Sub ViDu1()
Dim wb As Workbook
Dim wsInput As Worksheet
Dim wsOutput As Worksheet
Dim rowCount As Integer
Dim colCount As Integer
Dim i As Integer
Dim j As Integer
On Error GoTo ErrorProcess
' assign wb to active workbook
Set wb = Application.ActiveWorkbook
' delete sheet "output" if existed
For i = 1 To wb.Worksheets.Count
If wb.Sheets(i).Name = SHEET_OUTPUT Then
Application.DisplayAlerts = False
wb.Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
' copy sheet "input" and change to "output"
Set wsInput = wb.Sheets(SHEET_INPUT)
wsInput.Copy After:=wsInput
Set wsOutput = wb.Sheets(SHEET_INPUT & " (2)")
wsOutput.Name = SHEET_OUTPUT
' count row
rowCount = wsOutput.Range("A1", wsOutput.Range("A1").End(xlDown)).Rows.Count
' count col
colCount = wsOutput.Range("A1", wsOutput.Range("A1").End(xlToRight)) _
.Columns.Count
' if cell value equals empty, assign that cell to 0 value
For i = 1 To rowCount
For j = 1 To colCount
If wsInput.Cells(i, j) = "" Then
wsOutput.Cells(i, j) = 0
wsOutput.Cells(i, j).Interior.ColorIndex = 37
End If
Next j
Next i
GoTo EndSub
ErrorProcess:
MsgBox Err.Number & ": " & Err.Description
EndSub:
Set wsOutput = Nothing
Set wsInput = Nothing
Set wb = Nothing
End Sub