我有一部分代码供VBA运行,并在我的数据中找到非连续数字后添加空白行。但是,我的数据包含字母和代码编写方式,它只比较整数序列。有没有办法操纵代码只选择部分单元格并比较该部分?
例如,我有以下顺序:
100-CG-000-10008
100-CG-000-10009
100-CG-000-10011
100-CG-000-10012
并且想法是让VBA在 100-CG-000-10009 之后插入一个空白行,因为之后不再按顺序排列。我正在使用的代码是:
Sub InsertNullBetween()
'Update 20130829
Dim WorkRng As Range
Dim Rng As Range
Dim outArr As Variant
Dim dic As Variant
Set dic = CreateObject("Scripting.Dictionary")
'On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
num1 = WorkRng.Range("A1").Value
num2 = WorkRng.Range("A" & WorkRng.Rows.Count).Value
interval = num2 - num1
ReDim outArr(1 To interval + 1, 1 To 2)
For Each Rng In WorkRng
dic(Rng.Value) = Rng.Offset(0, 1).Value
Next
For i = 0 To interval
If dic.Exists(i + num1) Then
outArr(i + 1, 1) = i + num1
outArr(i + 1, 2) = dic(i + num1)
Else
outArr(i + 1, 1) = ""
outArr(i + 1, 2) = ""
End If
Next
With WorkRng.Range("A1").Resize(UBound(outArr, 1), UBound(outArr, 2))
.Value = outArr
.Select
End With
End Sub
有没有办法可以改变代码只看第3个“ - ”之后包含整数的单元格的最后部分?
答案 0 :(得分:0)
您的代码看起来太复杂了。在这里,我将只提供从您的单元格中提取最后一个“ - ”之后的最后一个数字的方法:
Function ExtractNumber(r As Range) As Long
ExtractNumber = Mid(r.Value, 1 + InStrRev(r.Value, "-"))
End Function
假设您的当前代码在纯数字的单元格中运行良好,您可以使用此函数进行自定义。例如:
num1= ExtractNumber(WorkRng.Range("A1"))
num2 = ExtractNumber(WorkRng.Range("A" & WorkRng.Rows.Count))
...
dic(ExtractNumber(Rng)) = Rng.Offset(0, 1).Value
等。
答案 1 :(得分:0)
编辑,其代码只能插入行并处理任何差距
你可以用这个
Option Explicit
Sub InsertNullBetween()
Dim i As Long, gap As Long
With Range("A1", Cells(Rows.count, 1).End(xlUp))
For i = .Rows.count To 2 Step -1
gap = Right(.Cells(i), 5) - Right(.Cells(i - 1), 5)
If gap > 1 Then .Cells(i).Resize(gap - 1).Insert xlDown
Next
End With
End Sub