【问题标题】:EXCEL VBA help - function to insert blank cellEXCEL VBA 帮助 - 插入空白单元格的功能
【发布时间】:2010-06-04 11:44:49
【问题描述】:

我需要一些有关 excel VBA 函数的帮助。

我有这样的数据

    ColA     ColB
    a123     a123
    a124     a124
    a127     a126
    a128     a127
    ....     ....

我想比较 ColA 和 ColB 的内容,如果内容不同,我想在 A 列中插入一个空白单元格。所以结果将如下所示:

ColA     ColB
a123     a123
a124     a124
         a126
a127     a127
....     ....

关于如何在 Excel 中执行此操作的任何建议。

提前致谢


更新


我用下面的代码尝试了下面的方法来插入单元格,它工作正常,我现在意识到当我运行它时我需要更多的功能。

first_col.Cells(row, 1).Select
Selection.Insert Shift:=xlDown

如果删除“a”的 ColA 中的值小于删除“a”的 ColB 中的值,我想在 ColA 中插入单元格,并且我还需要在 ColC 中的相同位置插入一个单元格(包含其他数据)。如果 ColB 的值更大,我只想在 ColB 中插入单元格。我想我知道在 If 语句中该做什么,但我不确定如何构造 IF。这是我的想法

Set other_col = Range("C1:C100")

//if substring of ColA > substring of ColB
   first_col.Cells(row, 1).Select
   Selection.Insert Shift:=xlDown
   other_col.Cells(row, 1).Select
   Selection.Insert Shift:=xlDown
//else 
   second_col.Cells(row, 1).Select
   Selection.Insert Shift:=xlDown

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您的比较语句可能如下所示:

    Sub Expand()
    
        Dim first_col As Range, cell As Range
        Dim row As Integer
    
        Set first_col = Range("A2:A100")
    
        For Each cell In first_col
            If Right(cell.Value, 3) < Right(cell.Offset(0, 1).Value, 3) Then
                ' Shift in here
            End If
        Next cell
    
    End Sub
    

    “Right”函数查看第二个参数指定的右边的字符数。

    另一个注意事项是这样的代码部分使用 .select 方法:

    first_col.Cells(row, 1).Select
    Selection.Insert Shift:=xlDown
    

    可以这样截断:

    first_col.cells(row, 1).insert shift:=xlDown
    

    “选择”和“选择”是宏记录器的剩余部分,通常不在 VBA 代码中使用。

    【讨论】:

      【解决方案2】:

      我不知道插入行的确切 VBA 代码,但您可以通过录制宏找到它。以下是其余代码(循环列并进行比较):

      Sub Expand()
          Dim first_col as Range
          Dim second_col as Range
          Dim row as Integer
      
          Set first_col = Range("A2:A100")
          Set second_col = Range("B2:B100")
      
          For row = 1 To second_col.Rows.Count
              If first_col.Cells(Row, 1).Value <> second_col.Cells(Row, 1).Value Then
                  '// code to insert the row'
              End If
          Next row
      End Sub
      

      【讨论】:

      • 我已经用更多细节更新了上面的问题,感谢您的回复,这肯定是我需要的一部分
      【解决方案3】:

      我通过选择一些单元格并插入来录制宏 我尝试创建自己的 sub 并且它可以工作

      Range("c16:e16").Select
      Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
      

      编辑注释 此代码导致 unmerg 合并单元格

      【讨论】:

        猜你喜欢
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多