Viết thủ tục Sắp xếp dữ liệu

  • Thread starter Tuanktcdcn
  • Ngày gửi
T

Tuanktcdcn

Lão già ham vui
18/6/04
549
52
28
47
Hà Nội
www.bluesofts.net
Tớ có vấn đề này muốn tham khảo cách làm của mọi người. Đó là thủ tục sắp xếp dữ liệu.

Level 1
Sub Sapxep1(Byref MangMotchieu, Optional Byval Tangdan as Boolean=True)
....Bạn làm thế nào?
End Sub


Áp dụng: Thủ tục Sapxep1 cho phép bạn sắp xếp dữ liệu được đặt trong một mảng một chiều, kết quả thực hiện MangMotchieu được sắp xếp theo chiều tăng dần hoặc giảm dần.

Cách test, mình viết thủ tục để các bạn test kết quả của Sapxep1
==============Test For Sapxep1==============
Sub TestForSapxep1()
Const strSheet="Tên sheet để ghi kết quả"
Dim WS as Worksheet
Dim MangMotchieu(5)

MangMotchieu(1)=2
MangMotchieu(2)=1
MangMotchieu((3)=6
MangMotchieu(4)=0
MangMotchieu(5)=6

Set WS = Worksheets(strSheet)

'Sắp xếp tăng dần bằng thủ tục Sapxep1

Sapxep1 MangMotchieu

WS.Cells.Clear
For I=1 to 5
WS.Cells(I,1).Value=MangMotchieu(I)
End For

Set WS = Nothing
End Sub
========================================

Level 2

Sub Sapxep2(Byref MangHaichieu, Byaval CotSapxep as Integer, Optional Byval Tangdan as Boolean=True)
....Bạn làm thế nào?
End Sub


Áp dụng: Một bảng dữ liệu mà các bạn nhìn trên Sheet có thể hiểu nó là khối dữ liệu được đặt trong bảng 2 chiều (Dòng, Cột). Thủ tục Sapxep2 cho phép bạn sắp xếp dữ liệu được đặt trong một mảng hai chiều, kết quả thực hiện MangHaichieu được sắp xếp theo chiều tăng dần hoặc giảm dần theo một cột nào đó.
Giả sử mình có một bảng Danh mục hàng
| Mã hàng | Tên hàng | ĐV |
Cần sắp xếp bảng dữ liệu trên

Cách test, mình viết thủ tục để các bạn test kết quả của Sapxep2
==============Test For Sapxep2==============
Sub TestForSapxep2()
Const nCotSapxep=2
Const strSheet="Tên sheet để ghi kết quả"
Dim WS as Worksheet
Dim MangHaichieu(5,3) '5 dòng và 3 cột

MangHaichieu(1,1)="HH001" : MangHaichieu(1,2)="Chỉ khâu" : MangHaichieu(1,3)="Cuộn"
MangHaichieu(2,1)="HH002" : MangHaichieu(2,2)="Kim băng" : MangHaichieu(1,3)="Hộp"
MangHaichieu(3,1)="HH003" : MangHaichieu(3,2)="Vải Coton L3" : MangHaichieu(1,3)="m2"
MangHaichieu(4,1)="HH004" : MangHaichieu(4,2)="Vải Coton L1" : MangHaichieu(1,3)="m2"
MangHaichieu(5,1)="HH005" : MangHaichieu(5,2)="Vải Coton L2" : MangHaichieu(5,3)="m2"

Set WS = Worksheets(strSheet)

'Sắp xếp tăng dần mảng MangHaichieu bằng thủ tục Sapxep2 theo cột "Tên hàng"

Sapxep2 MangHaichieu, CotSapxep

WS.Cells.Clear
For I=1 To 5
For J=1 To 3
WS.Cells(I,J).Value=MangHaichieu(I,J)
End For
End For

Set WS = Nothing
End Sub
========================================
Trong lập trình VBA, việc sắp xếp mà dùng theo Sort của Excel không phải cách tốt (nó thuộc phạm vi ứng dụng người dùng) nên cần làm trong VBA.
Mình đã làm việc này rồi và có kết quả. Tuy nhiên rất muốn tham khảo các cách làm của các bạn để chọn ra một cách làm tối ưu nhất. Mình sẽ gửi cách của mình lên sau.
 
Khóa học Quản trị dòng tiền
Đào Việt Cường

Đào Việt Cường

Moderator
22/11/05
400
4
18
Khánh Hòa
Dear Lão già!!!:dzo:
--------------
Em tưởng bác muốn sắp sếp các Item trong ListBox/ComboBox giống như "fu quân của Eva" chứ. Nếu làm trên MSE thì sao không tận dụng phương thức sort của Range (nói chung)?
Này nhé:
VBA Assistant nói:
Sorts a PivotTable report, a range, or the active region if the specified range contains only one cell.
expression.Sort(Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3)
expression Required. An expression that returns one of the objects in the Applies To list.
Key1 Optional Variant. The first sort field, as either text (a PivotTable field or range name) or a Range object ("Dept" or Cells(1, 1), for example).
Order1 Optional XlSortOrder. The sort order for the field or range specified in Key1.
XlSortOrder can be one of these XlSortOrder constants.xlDescending. Sorts Key1 in descending order.xlAscending default. Sorts Key1 in ascending order.
Key2 Optional Variant. The second sort field, as either text (a PivotTable field or range name) or a Range object. If you omit this argument, there’s no second sort field. Cannot be used when sorting Pivot Table reports.
Type Optional Variant. Specifies which elements are to be sorted. Use this argument only when sorting PivotTable reports.
XlSortType can be one of these XlSortType constants.xlSortLabels. Sorts the PivotTable report by labels.xlSortValues. Sorts the PivotTable report by values.
Order2 Optional XlSortOrder. The sort order for the field or range specified in Key2. Cannot be used when sorting PivotTable reports.
XlSortOrder can be one of these XlSortOrder constants.xlDescending. Sorts Key2 in descending order.xlAscending default. Sorts Key2 in ascending order.
Key3 Optional Variant. The third sort field, as either text (a range name) or a Range object. If you omit this argument, there’s no third sort field. Cannot be used when sorting PivotTable reports.
Order3 Optional XlSortOrder. The sort order for the field or range specified in Key3. Cannot be used when sorting PivotTable reports.
XlSortOrder can be one of these XlSortOrder constants.xlDescending. Sorts Key3 in descending order.xlAscending default. Sorts Key3 in ascending order.
Header Optional XlYesNoGuess. Specifies whether or not the first row contains headers. Cannot be used when sorting PivotTable reports.
XlYesNoGuess can be one of these XlYesNoGuess constants.xlGuess. Let Microsoft Excel determine whether there’s a header, and to determine where it is, if there is one.xlNo default. (The entire range should be sorted).xlYes. (The entire range should not be sorted).
OrderCustom Optional Variant. This argument is a one-based integer offset to the list of custom sort orders. If you omit OrderCustom , a normal sort is used.
MatchCase Optional Variant. True to do a case-sensitive sort; False to do a sort that’s not case sensitive. Cannot be used when sorting PivotTable reports.
Orientation Optional XlSortOrientation. The sort orientation.
XlSortOrientation can be one of these XlSortOrientation constants.xlSortRows default. Sorts by row.xlSortColumns. Sorts by column.
SortMethod Optional XlSortMethod. The type of sort. Some of these constants may not be available to you, depending on the language support (U.S. English, for example) that you’ve selected or installed.
XlSortMethod can be one of these XlSortMethod constants.xlStroke Sorting by the quantity of strokes in each character.xlPinYin default. Phonetic Chinese sort order for characters.
DataOption1 Optional XlSortDataOption. Specifies how to sort text in key 1. Cannot be used when sorting PivotTable reports.
XlSortDataOption can be one of these XlSortDataOption constants.xlSortTextAsNumbers. Treat text as numeric data for the sort.xlSortNormal default. Sorts numeric and text data separately.
DataOption2 Optional XlSortDataOption. Specifies how to sort text in key 2. Cannot be used when sorting PivotTable reports.
XlSortDataOption can be one of these XlSortDataOption constants.xlSortTextAsNumbers. Treats text as numeric data for the sort.xlSortNormal default. Sorts numeric and text data separately.
DataOption3 Optional XlSortDataOption. Specifies how to sort text in key 3. Cannot be used when sorting PivotTable reports.
XlSortDataOption can be one of these XlSortDataOption constants.xlSortTextAsNumbers. Treats text as numeric data for the sort.xlSortNormal default. Sorts numeric and text data separately.
Remarks
The settings for Header, Order1, Order2, Order3, OrderCustom, and Orientation are saved, for the particular worksheet, each time you use this method. If you don’t specify values for these arguments the next time you call the method, the saved values are used. Set these arguments explicitly each time you use Sort method, if you choose not to use the saved values.
Text strings which are not convertible to numeric data are sorted normally.
Note If no arguments are defined with the Sort method, Microsoft Excel will sort the selection, chosen to be sorted, in ascending order.


Bác thấy nhức đầu chưa!
Nhưng ví dụ thì đơn giản thế này:
VBA Assistant nói:
This example sorts the range A1:C20 on Sheet1, using cell A1 as the first sort key and cell B1 as the second sort key. The sort is done in ascending order by row, and there are no headers. This example assumes there is data in the range A1:C20.
Sub SortRange1()
Worksheets("Sheet1").Range("A1:C20").Sort _
Key1:=Worksheets("Sheet1").Range("A1"), _
Key2:=Worksheets("Sheet1").Range("B1")
End Sub

Theo em thì bác đã cưới MSE rồi thì đừng ly dị chị ấy!
 
T

Tuanktcdcn

Lão già ham vui
18/6/04
549
52
28
47
Hà Nội
www.bluesofts.net
Cường chưa hiểu ý anh rồi!
Trong lập trình VBA, việc sắp xếp mà dùng theo Sort của Excel không phải cách tốt (nó thuộc phạm vi ứng dụng người dùng) nên cần làm trong VBA.

Trong xử lý dữ liệu, có rất nhiều dữ liệu trung gian cần làm, không phải lúc nào mình cũng đổ hết dữ liệu ra một Sheet nháp gọi là (TempSh) để dùng Sort cả. Phần nữa, việc sắp xếp nhiều khi để giải quyết một khâu nào đó trong một chuỗi các công việc, nếu dùng Sort sẽ làm thay đổi trạng thái Sheet của người dùng mà họ lại không muốn thế!

Trong Excel, quan điểm của anh là vận dụng tối đa từ ứng dụng người dùng mới đến VBA, như thế mới "kinh tế"!

mysterious_girl nói:
Đây có phải là bài tập VBA cho buổi thứ 2 không, anh nhỉ?
Hi, em cho thế thì là thế đi! Riêng em mà làm được anh sẽ có quà.
 
adam_tran

adam_tran

Guitar inspiration
17/5/05
1,374
36
48
46
Goooogle
Ý em cũng thế, để xuất dữ liệu ra 1 mảng hay 1 sheet rồi ứng dụng các công cụ có sẳn cũng hay, nhưng đôi lúc không thỏa mãn sở thích "vọc cho biết".
Em đang search tìm 1 Data Control nào đó rồi dùng các phương thức sẳn có để sort, chẳng hạn MSFlexGrid (mà chẳng hiểu sao Office của em không cho dùng MSFkexGrid với lý do không có bản quyền). MSForm ListBox và ComboBox cũng store cả 1 mảng dữ liệu, nhưng nó không support phương thức sort mà thôi, do đó em cho là sẽ có 1 control nào đó có phương thức này.
MysteriousGirl nói:
Đây có phải là bài tập VBA cho buổi thứ 2 không, anh nhỉ

Bài tập kiểu này thì quá khả năng của lớp 2 rồi, nó vừa có mảng, lại có ByVal lại Optional Nó là vấn đề của các cao thủ đấy. Anh post ở đây cũng chỉ là spam cho xôm thôi.
 
Sửa lần cuối:
Đào Việt Cường

Đào Việt Cường

Moderator
22/11/05
400
4
18
Khánh Hòa
adam_tran nói:
em cho là sẽ có 1 control nào đó có phương thức này.
Dear adam_tran,
---------------
Anh đã xem qua TrueDBGrid.OCX chưa? Em thấy cái này làm được nhiều việc lắm, kể cả đưa Validation vào trong Grid giống như Excel. Với phiên bản mới (9.0 thì phải), nó còn cho Conditional Format. Nhưng phiên bản này phải mua bản quyền. Em có bản có phiên bản 6.0 có "key", anh muốn nghiên cứu thì em gửi cho!
 
hai2hai

hai2hai

VNUNI Makes a difference
29/4/04
2,032
125
63
50
Hà nội
vnuni.net
Đào Việt Cường nói:
Dear adam_tran,
---------------
Anh đã xem qua TrueDBGrid.OCX chưa? Em thấy cái này làm được nhiều việc lắm, kể cả đưa Validation vào trong Grid giống như Excel. Với phiên bản mới (9.0 thì phải), nó còn cho Conditional Format. Nhưng phiên bản này phải mua bản quyền. Em có bản có phiên bản 6.0 có "key", anh muốn nghiên cứu thì em gửi cho!

:)

Tất cả các Grid trên đời này (cả trên .NET) h2h đều có (có cả Se***ial, latest verison) nhưng ko muốn dùng cho các ứng dụng Commercial Packages của mình mà chỉ dùng để evaluate thôi (và nếu dùng thì chắc sau phải mua tử tế).

TrueDBGrid cũng là 1 trong các Grid đó, tuy khá nhiều features nhưng cái này hơi nặng nề (đã dùng các công cụ xịn để test trên mọi phương diện rồi, toàn chuyên gia đánh giá & evaluate thôi). Hiện truedb suite đã được componentone mua rồi và tất cả các controls có trademark là TrueDB đều nằm trong bộ ComponentOne Suite.

Bây giờ công nghệ Grid phát triển mạnh mẽ lắm. Nhiều features thuộc dạng trước kia chỉ nằm mơ thôi, giờ có hết mà chẳng phải lập trình gì cả.

Tham khảo: http://www.componentsource.com/features/xgrids/index.html

Ví dụ:
512926.gif


Còn đây là cái TrueDB Grid này, trông ... rõ chán:
510700.gif


Nhưng VSFlexGrid của ComponentOne thì luôn là sự lựa chọn số 1:
504721.gif
 
Sửa lần cuối:
M

mysterious_girl

Guest
Tuanktcdcn nói:
Hi, em cho thế thì là thế đi! Riêng em mà làm được anh sẽ có quà.

Cám ơn anh nhiều. Nhưng trình độ của em chỉ ở mức a bờ cờ thì làm sao dám làm bài này của anh,hic!!!:friend:
 

Xem nhiều

Webketoan Zalo OA