- Tham gia
- 8/6/06
- Bài viết
- 14,637
- Được thích
- 22,970
- Nghề nghiệp
- U80
Phần giới thiệu nguồn tài nguyên trên mạng:
One of the most beneficial Methods in Excel (in my experience) is the SpecialCells Method. When used, it returns a Range Object that represents only those type of cells we specify. For example, one can use the SpecialCells Method to return a Range Object that only contains formulae. In fact, we can, if we wish, even narrow it down further to have our Range Object (containing only formulae) to return only formulae with errors.
The syntax for the SpecialCells Method is;
expression.SpecialCells(Type, Value)
Where "expression" must be a Range Object. For example Range("A1:C100"), ActiveSheet.UsedRange etc.
Type=XlCellType and can be one of these XlCellType constants.
xlCellTypeAllFormatConditions. Cells of any format
xlCellTypeAllValidation. Cells having validation criteria
xlCellTypeBlanks. Empty cells
xlCellTypeComments. Cells containing notes
xlCellTypeConstants. Cells containing constants
xlCellTypeFormulas. Cells containing formulas
xlCellTypeLastCell. The last cell in the used range. Note this XlCellType will include empty cells that have had any of cells default format changed.
xlCellTypeSameFormatConditions. Cells having the same format
xlCellTypeSameValidation. Cells having the same validation criteria
xlCellTypeVisible. All visible cells
These arguments cannot be added together to return more than one XlCellType.
Value=XlSpecialCellsValue and can be one of these XlSpecialCellsValue constants.
xlErrors
xlLogical
xlNumbers
xlTextValues
These arguments can be added together to return more than one XlSpecialCellsValue.
The SpecialCells Method can be used in a wide variety of situations when you only need to work with cells housing specific types of data. For example, the code below would return a Range Object representing all formulae on the active Worksheet.
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas)
If we wanted, we could narrow this down further to only return a Range Object representative of all formulae that are returning numbers.
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas,xlNumbers)
Once we have the specific Range Object type returned we can then work with only those cells. This can often be done in one line of code, or you may need to loop through the range. See examples below;
Although I have used a loop on the second macro, so that all returned numbers are converted to their negative counterparts, we could make use of PasteSpecial to do so without looping and allow the formulae to remain in the cells. That is;
SpecialCells Gotcha!
If you are familiar with Excel and it's built in features, such as SpecialCells, you will know that when/if one specifies only a single cell (via Selection or Range) Excel will assume you wish to work with the entire Worksheet of cells. For example, the 2 macros below would both select ALL blank cells on a Worksheet.
So, as you can see, specifying only a single cell Range can give unwanted results.
SpecialCells for Formulae & Constants
While we cannot specify more than one XlCellType (e.g. xlCellTypeConstants+xlCellTypeFormulas would fail) we can use the SpecialCells method to return only used cells housing numbers on a Worksheet (formulae & constants) and omit any cells containing text (formulae & constants).
You should take note of the On Error Resume Next statement in the above code. This is needed as when the SpecialCells Method condition cannot be met an error occurs. As you may, or may not know, a non valid Range Object returns the Nothing keyword. After Setting a Range variable to the SpecialCells Method we need to then check that we have been able to pass a Range Object to our Range variable. It is the If Statement (and 2 ElseIf) that checks this in the code above.
(Tại: http://www.ozgrid.com/forum/showthread.php?t=61732&highlight=specialcells)
Phần giúp đỡ trong cửa sổ VBA:
Bạn vô CS (cửa sổ) VBA bằng tổ hợp fím ALT+{F11} & nhập các kí tự sau: SpecialCells. Sau đó bôi toàn bộ tên phương thức & nhấn {F1} để được excel giải thích; Tuy nhiên giải thích này có thể làm chúng ta cảm thấy không đủ so với những gì đã ghi trên diễn đàn đã nêu như trên;
/(/hững áp dụng cụ thể
A. Ta xem lại lần lượt các ví dụ nêu trên:
1.- Tô màu nền cho các ô trống trong vùng sử dụng
Giả dụ trên trang tính trắng ta nhập ‘Nam’ vô ô B2; ‘Thanh’ vô C3 & ‘Chanh’ vô ô D4 & cho chạy macro ColorAllFormulae để biết xem những ô nào được tô màu nền?!
2.- Đổi dấu dữ liệu của các ô công thức
Bằng cách sử dụng một trong hai macro đã nêu NegativeAllNumberFormula & NegativeAllNumberFormula2
3.- Các trường hợp đếm các ô không chứa dữ liệu
Để hiểu rõ hơn về câu lệnh UsedRange.SpecialCells(x) ta xét đến ví dụ sau: Ta có trang tính trắng; Tại D4 ta nhập tên ‘Lê’; ô D5 nhập ‘Hoa’ & ô D6 ta nhập =D4 & “ “ & D5. Sau đó cho chạy macro sau:
4.- Chọn vùng dữ liệu chứa công thức hay trị kiểu số
Bằng macro AllNummericCells
B. Ta xem các phương án ứng dụng khác nhau trong 1 macro sau đây:
Tiếp phần 2
Mã:
[size=2][b] The SpecialCells Method in Excel VBA[/b][/size]
The syntax for the SpecialCells Method is;
expression.SpecialCells(Type, Value)
Where "expression" must be a Range Object. For example Range("A1:C100"), ActiveSheet.UsedRange etc.
Type=XlCellType and can be one of these XlCellType constants.
xlCellTypeAllFormatConditions. Cells of any format
xlCellTypeAllValidation. Cells having validation criteria
xlCellTypeBlanks. Empty cells
xlCellTypeComments. Cells containing notes
xlCellTypeConstants. Cells containing constants
xlCellTypeFormulas. Cells containing formulas
xlCellTypeLastCell. The last cell in the used range. Note this XlCellType will include empty cells that have had any of cells default format changed.
xlCellTypeSameFormatConditions. Cells having the same format
xlCellTypeSameValidation. Cells having the same validation criteria
xlCellTypeVisible. All visible cells
These arguments cannot be added together to return more than one XlCellType.
Value=XlSpecialCellsValue and can be one of these XlSpecialCellsValue constants.
xlErrors
xlLogical
xlNumbers
xlTextValues
These arguments can be added together to return more than one XlSpecialCellsValue.
The SpecialCells Method can be used in a wide variety of situations when you only need to work with cells housing specific types of data. For example, the code below would return a Range Object representing all formulae on the active Worksheet.
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas)
If we wanted, we could narrow this down further to only return a Range Object representative of all formulae that are returning numbers.
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas,xlNumbers)
Once we have the specific Range Object type returned we can then work with only those cells. This can often be done in one line of code, or you may need to loop through the range. See examples below;
Mã:
Sub ColorAllFormulae()
ActiveSheet.UsedRange.SpecialCells _
(xlCellTypeFormulas).Interior.ColorIndex = 36
End Sub
Sub NegativeAllNumberFormula()
Dim rRange As Range, rCell As Range
Set rRange = ActiveSheet.UsedRange.SpecialCells _
(xlCellTypeFormulas, xlNumbers)
For Each rCell In rRange
rCell = rCell.Value * -1
Next rCell
End Sub
Mã:
Sub NegativeAllNumberFormula2()
With Range("IV65536")
.Value = -1
.Copy
ActiveSheet.UsedRange.SpecialCells _
(xlCellTypeFormulas, xlNumbers).PasteSpecial _
xlPasteValues, xlPasteSpecialOperationMultiply
.Clear
End With
End Sub
If you are familiar with Excel and it's built in features, such as SpecialCells, you will know that when/if one specifies only a single cell (via Selection or Range) Excel will assume you wish to work with the entire Worksheet of cells. For example, the 2 macros below would both select ALL blank cells on a Worksheet.
Mã:
Sub SelectAllBlanks()
ActiveSheet.UsedRange.SpecialCells(xlCellTypeBlanks).Select
End Sub
Sub SelectAllBlanks2()
Range("A1").SpecialCells(xlCellTypeBlanks).Select
End Sub
SpecialCells for Formulae & Constants
While we cannot specify more than one XlCellType (e.g. xlCellTypeConstants+xlCellTypeFormulas would fail) we can use the SpecialCells method to return only used cells housing numbers on a Worksheet (formulae & constants) and omit any cells containing text (formulae & constants).
Mã:
Sub AllNummericCells()
Dim rCcells As Range, rFcells As Range
Dim rAcells As Range
[color="Blue"]'Set variable to all used cells [/color]
Set rAcells = ActiveSheet.UsedRange
On Error Resume Next 'In case of no numeric formula or constants.
[color="Blue"]'Set variable to all numeric constants[/color]
Set rCcells = rAcells.SpecialCells(xlCellTypeConstants, xlNumbers)
'Set variable to all numeric formulas
Set rFcells = rAcells.SpecialCells(xlCellTypeFormulas, xlNumbers)
[COLOR="Blue"]'Determine which type of numeric data (formulas, constants or none)[/COLOR]
If rCcells Is Nothing And rFcells Is Nothing Then
MsgBox "You Worksheet contains no numbers"
End
ElseIf rCcells Is Nothing Then
Set rAcells = rFcells [color="Blue"] 'formulas[/color]
ElseIf rFcells Is Nothing Then
Set rAcells = rCcells [color="Blue"]'constants [/color]
Else
Set rAcells = Application.Union(rFcells, rCcells) [color="Blue"] 'Both[/color]
End If
On Error GoTo 0
rAcells.Select
End Sub
(Tại: http://www.ozgrid.com/forum/showthread.php?t=61732&highlight=specialcells)
Phần giúp đỡ trong cửa sổ VBA:
Bạn vô CS (cửa sổ) VBA bằng tổ hợp fím ALT+{F11} & nhập các kí tự sau: SpecialCells. Sau đó bôi toàn bộ tên phương thức & nhấn {F1} để được excel giải thích; Tuy nhiên giải thích này có thể làm chúng ta cảm thấy không đủ so với những gì đã ghi trên diễn đàn đã nêu như trên;
/(/hững áp dụng cụ thể
A. Ta xem lại lần lượt các ví dụ nêu trên:
1.- Tô màu nền cho các ô trống trong vùng sử dụng
Giả dụ trên trang tính trắng ta nhập ‘Nam’ vô ô B2; ‘Thanh’ vô C3 & ‘Chanh’ vô ô D4 & cho chạy macro ColorAllFormulae để biết xem những ô nào được tô màu nền?!
2.- Đổi dấu dữ liệu của các ô công thức
Bằng cách sử dụng một trong hai macro đã nêu NegativeAllNumberFormula & NegativeAllNumberFormula2
3.- Các trường hợp đếm các ô không chứa dữ liệu
Để hiểu rõ hơn về câu lệnh UsedRange.SpecialCells(x) ta xét đến ví dụ sau: Ta có trang tính trắng; Tại D4 ta nhập tên ‘Lê’; ô D5 nhập ‘Hoa’ & ô D6 ta nhập =D4 & “ “ & D5. Sau đó cho chạy macro sau:
Mã:
[b]
Sub CountAllBlanks()[/b]
ActiveSheet.UsedRange.SpecialCells(xlCellTypeBlanks).Select: MsgBox Selection.Count
Range("A1").SpecialCells(xlCellTypeBlanks).Select: MsgBox Selection.Count
[b]End Sub [/b]
Bằng macro AllNummericCells
B. Ta xem các phương án ứng dụng khác nhau trong 1 macro sau đây:
Mã:
[b]Sub FillBlanks()[/b]
Dim Rng As Range: Dim iZ As Integer
iZ = InputBox("CHON PHUONG AN:", , "9")
Select Case iZ
Case 1 [color="Blue"]’a: Nhập trị ‘0’ cho toàn thể các ô trống trong vùng chọn [/color]
Range("C1:D9").SpecialCells(xlCellTypeBlanks).Value = 0
Case 2 [color="Blue"]’b: Xóa giá trị các ô trên cột ‘A’ tương ứng với các ô trên cột B là trống [/color]
Columns("B:B").SpecialCells(xlCellTypeBlanks).Offset(0, -1).ClearContents
Case 3[color="Blue"] ‘c: Ẩn/Xóa các dòng trong vùng từ 10 đến 40 khi ô trên cột A tương ứng là trống [/color]
Set Rng = Range("A10:A40").SpecialCells(xlBlanks).EntireRow
Rng.Hidden = True
' Range("A10:A40").SpecialCells(xlBlanks).EntireRow.Delete
Case 4 [color="Blue"] ‘d: Hiện số dòng & địa chỉ của chúng, khi chúng không ẩn[/color]
Set Rng = ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible).Rows
MsgBox ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible).Rows.Count, , Rng.Address
Case 5[color="Blue"] ‘đ: Xóa giá trị các ô chứa số liệu, nhưng không là công thức [/color]
ActiveSheet.Cells.SpecialCells(xlCellTypeConstants, 23).ClearContents
Case 6[color="Blue"] ‘e: Xóa giá trị các ô chứa số liệu trong vùng đặt tên [b]‘ConstantRef’[/b] [/color]
On Error Resume Next
Range("ConstantRef").SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
'[Color="Blue"] * * * Thêm Mới [/Color]
Case 7
Dim lLastRow As Long, iLastCol As Integer
Set Rng = Range("A1").SpecialCells(xlCellTypeLastCell)
lLastRow = Rng.Row: iLastCol = Rng.Column
MsgBox Rng.Address, , Str(lLastRow) & Str(iLastCol)
Case 8
For Each Rng In Cells.SpecialCells(xlCellTypeConstants, xlNumbers)
If Not IsDate(Rng.Value) Then Rng.ClearContents
Next Rng
'[Color="Blue"] * * * [/Color]
case else
End Select
[b]End Sub[/b]
Tiếp phần 2
Lần chỉnh sửa cuối: