Lập trình VBA Shuffle trong Excel
Dưới đây là đoạn mã tôi đã tạo để xáo trộn các ô trong phạm vi được chỉ định. Tôi không chắc lỗi ở đâu vì nó chỉ xáo trộn các ô từ C19 đến C29. Tôi đã thử một số biến thể khác nhưng chúng lại khiến các cột nằm giữa C, F, I, L và O cũng bị xáo trộn. Tôi chỉ muốn các ô C19:C29, F19:F29, I19:I29, L19:L29, O19:O29 là những ô được xáo trộn. Ngoài ra, tôi không muốn giá trị trong C19:C29 chuyển sang F19:F29 hoặc ngược lại. Giá trị trong cột cần phải giữ nguyên trong cột đó. Nếu bạn có thể giúp thêm hoặc xóa mã để thực hiện việc này thì thật tuyệt vời! Cảm ơn!
Public Sub ShuffleGrid()
Trang tính ("mẫu").Chọn
Dim rngSelected As Range
Đặt rngSelected = Range("C19:C29, F19:F29, I19:I29, L19:L29, O19:O29")
'
Macro xáo trộn
'
'
Chiều dài ngang nhỏ
Dim verticalLength As Long
horizontalLength = rngSelected.Columns.Count
Chiều dài dọc = rngSelected.Rows.Count
Dim i As Long
Dim j As Long
Đối với i = verticalLength đến 1 Bước -1
Đối với j = horizontalLength đến 1 Bước -1
Dim rndRow As Long
Dim rndColumn As Long
rndRow = Application.WorksheetFunction.RoundDown(verticalLength * Rnd + 1, 0)
rndColumn = Application.WorksheetFunction.RoundDown(horizontalLength * Rnd + 1, 0)
Dim temp As String
Dim tempColor As Long
Dim tempFontColor As Long
temp = rngSelected.Cells(i, j).Formula
tempColor = rngSelected.Cells(i, j).Interior.Color
tempFontColor = rngSelected.Cells(i, j).Font.Color
rngSelected.Cells(i, j).Formula = rngSelected.Cells(rndRow, rndColumn).Formula
rngSelected.Cells(i, j).Interior.Color = rngSelected.Cells(rndRow, rndColumn).Interior.Color
rngSelected.Cells(i, j).Font.Color = rngSelected.Cells(rndRow, rndColumn).Font.Color
rngSelected.Cells(rndRow, rndColumn).Formula = temp
rngSelected.Cells(rndRow, rndColumn).Interior.Color = tempColor
rngSelected.Cells(rndRow, rndColumn).Font.Color = tempFontColor
Tiếp theo là j
Tiếp theo tôi
Trang tính ("mẫu").Chọn
End Sub
Comments
Post a Comment