|
本帖最后由 icxh 于 2025-3-15 09:01 编辑
如题。
想将所有行的数字加1、减1,并且按大小输出到下一行的指定位置,代码基本能执行,但是最后一行的结果始终无法输出。
详见附件。
还请大神指教。
代码如下
- Sub GenerateAdjacentNumbers()
- Dim ws As Worksheet
- Set ws = ThisWorkbook.Sheets("sheet1")
-
- Dim lastRow As Long
- lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
-
- Dim i As Long, j As Long, k As Long
- Dim prevNum As Integer, nextNum As Integer
- Dim dict As Object
- Dim arr() As Integer
- Dim outputCol As Integer
-
- For i = 4 To lastRow
- Set dict = CreateObject("Scripting.Dictionary")
-
- ' 处理前一行的8个号码
- For j = 2 To 9
- Dim currentNum As Integer
- currentNum = ws.Cells(i - 1, j).Value
-
- ' 计算前一个数字
- prevNum = currentNum - 1
- If nextNum = 0 Then nextNum = 50
- dict(nextNum) = 1
-
- ' 计算后一个数字
- nextNum = currentNum + 1
- If nextNum = 51 Then nextNum = 1
- dict(nextNum) = 1
-
- Next j
-
- ' 转换并排序数组
- ReDim arr(dict.Count - 1)
- k = 0
- For Each Key In dict.Keys
- arr(k) = Key
- k = k + 1
- Next
-
- ' 使用冒泡排序
- For m = LBound(arr) To UBound(arr) - 1
- For n = m + 1 To UBound(arr)
- If arr(m) > arr(n) Then
- temp = arr(m)
- arr(m) = arr(n)
- arr(n) = temp
- End If
- Next n
- Next m
-
- ' 输出结果到k列(第11列)
- outputCol = 11
- For m = 0 To UBound(arr)
- ws.Cells(i, outputCol + m).Value = arr(m)
- Next m
- Next i
-
- MsgBox "处理完成!"
- End Sub
复制代码
上传1.zip
(168.17 KB, 下载次数: 13)
|
|