根据相邻单元格中的值插入行数

时间:2018-04-03 20:50:38

标签: excel vba excel-vba

我已经调整了一个VB宏来在值之下插入额外的行(参见" interval"在A列中)当出现重复的关联值实例时(参见" count"在列中) C)。更具体地说,当存在大于1的重复计数(0 =无实例,1 =单个实例)且具有特定时间间隔时,我想插入额外的行,以便有空间插入重复的值他们的出现顺序。

Excel数据的图片before executionafter execution

以下是我一直在使用的代码,它似乎正在运行。但是,每次运行宏时它都会绘制一个错误代码。有人可以解释为什么这部分代码会触发错误,以及如何解决它?这是出现的错误代码:"运行时错误代码' 13'键入:mismatch",并调试指向此行代码:temp = Range("B" & n)

Sub dupeIntervals()
' insert new rows to match how many utterances are in a particular time interval
    Worksheets("Align").Activate
    Dim r, count As Range
    Dim LastRow As Long
    Dim temp As Integer
    Set r = Range("A:C")
    Set count = Range("B:B")
    LastRow = Range("B" & Rows.count).End(xlUp).Row
    For n = LastRow To 1 Step -1
        temp = Range("B" & n) ' << run-time error 13 / "type mismatch"
        If (temp > 1) Then
            Rows(n + 1 & ":" & n + temp - 1).Insert Shift:=xlDown
        End If
    Next n
End Sub

谢谢!

P.S。这是我如何使用这个宏的轶事解释: 我正在将转录访谈中的话语从连续数据(话语开始时的毫秒时间戳)转换为5秒的时间间隔。有时,每5秒间隔会有不止一个话语,这需要额外的行来在给定的时间间隔内插入那些额外的话语。

1 个答案:

答案 0 :(得分:2)

你的循环包括第1行:

LastRow To 1 Step -1

To 2 Step -1跳过标题。

那说......

您已将temp声明为Integer

Dim temp As Integer

这意味着您分配给temp的任何内容必须与16位有符号整数值兼容,即-32677和32767之间的任何数值。

某些值会隐式转换为Integer。例如44.634将为temp分配45。

但有些值不会转换。

  • 空字符串""(或任何非数字字符串)无法转换为Integer
  • 错误值(例如#NA)无法转换为任何

您的代码正在做出假设:

temp = Range("B" & n) ' << run-time error 13 / "type mismatch"

假设ActiveSheet是您要使用的工作表。假设n有一个表示有效工作表行号的值 - 您尚未声明n,因此它可能是Variant/LongVariant/Integer,因此{{1可能很好(仍然应该声明)。

假设范围的值可以强制转换为n

删除这些假设。

Integer

我建议使用32位整数类型(即Dim cellValue As Variant cellValue = ActiveSheet.Range("B" & n).Value If IsNumeric(cellValue) Then temp = CInt(cellValue) Else 'skip. cell is invalid. Debug.Print "Row# " & n & " contains an invalid value." End If )而不是Long

相关问题