enter image description here请我是Vba的新手。
我想要一个VBA从A1和B2输入的数据生成序列号。结果应该在另一个表A列中。
当我在A2和B2中输入另一个范围时,序列号应该在第一个序列号结束的地方继续。
内联图片
谢谢
答案 0 :(得分:0)
尝试一下,让我知道它是否适合您..这将为您提供图片中显示的结果。
Sub SerialCode()
Dim ws As Worksheet
Dim startOf As Long, endOf As Long, data 'startOf and endOf are Long for >5 digits.
Dim lastRow As Long, currentRow As Long
Dim dataRange As Range, c As Range
Set ws = ThisWorkbook.Sheets(1)
ws.Range("E2", ws.Cells(ws.Rows.Count, "E").End(xlUp)).Clear
ws.Range("F2", ws.Cells(ws.Rows.Count, "F").End(xlUp)).Clear
lastRow = 2
Set dataRange = ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp))
For Each c In dataRange
If c.Value <> "" Then
currentRow = c.Row
startOf = CLng(ws.Range("A" & currentRow).Value)
endOf = CLng(ws.Range("B" & currentRow).Value) + 1
If endOf <> 1 And startOf < endOf Then 'This will stop Overflow errors from occuring accidently
data = ws.Range("C" & currentRow).Value
Do While startOf <> endOf
ws.Range("E" & lastRow).Value = startOf
ws.Range("F" & lastRow).Value = data
startOf = startOf + 1
lastRow = lastRow + 1
Loop
Else: MsgBox "Ending Serial Number missing or is less than starting Serial Number on row " _
& c.Row, vbCritical, "Missing Data"
End If
End If
Next c
End Sub