Excel VBA,range.value = range.value,意外结果

时间:2014-11-28 15:13:10

标签: excel vba excel-vba

希望有人能够指出为什么这不起作用。基本上通过vba,在表的最后一行(Row41)插入一个新行,这会向下推动最后一行(在数据中创建一个间隙),然后将最后一行值向上传输一行,这样空行就在底部。

现在该过程正常工作,除了两个单元格值随机变化,下面是前后

在:

  • Cell(41,B)= 03/10/14
  • 细胞(41,C)= 12345
  • 细胞(41,E)= 3.00
  • 单元格(41,F)= DD

后:

  • Cell(41,B)= 03/10/14
  • 细胞(41,C)= 12345
  • 细胞(41,E)= 41915
  • 细胞(41,F)= 41915

我已经仔细检查了设定范围,他们应该是这样,任何想法?哦,对于代码,Specific_Tbl变量是2

    '[Capture table First/Last row number]
    int_FirstRow = .Cells(4, "AC").Offset(0, Specific_Tbl)
    int_LastRow = .Cells(6, "AC").Offset(0, Specific_Tbl)

    '[Insert Blank Row]
    .Range("A" & int_LastRow & ":Z" & int_LastRow).Insert shift:=xlDown

    '[Set Cell Ranges]
    Select Case Specific_Tbl
        Case 1
            '[Remerge Description]
            .Range(.Cells(int_LastRow, "E"), .Cells(int_LastRow, "H")).MergeCells = True
            Set rng_Tmp1 = .Range("B" & int_LastRow & ":C" & int_LastRow & ",E" & int_LastRow & ":J" & int_LastRow)
            Set rng_Tmp2 = .Range("B" & int_LastRow + 1 & ":C" & int_LastRow + 1 & ",E" & int_LastRow + 1 & ":J" & int_LastRow + 1)
        Case 2, 3
            Set rng_Tmp1 = .Range("B" & int_LastRow & ":C" & int_LastRow & ",E" & int_LastRow & ":F" & int_LastRow)
            Set rng_Tmp2 = .Range("B" & int_LastRow + 1 & ":C" & int_LastRow + 1 & ",E" & int_LastRow + 1 & ":F" & int_LastRow + 1)
    End Select

    '[Transfer values and clear]
    rng_Tmp1.Value = rng_Tmp2.Value
    rng_Tmp2.ClearContents

1 个答案:

答案 0 :(得分:0)

不幸的是,我从未发现为什么excel vba无法像我认为的那样处理分割范围。通过添加更多范围变量来处理分割范围的每一边来完成解决方法。

    '[Capture table First/Last row number]
    int_FirstRow = .Cells(4, "AC").Offset(0, Specific_Tbl)
    int_LastRow = .Cells(6, "AC").Offset(0, Specific_Tbl)

    '[Insert Blank Row]
    .Range("A" & int_LastRow & ":Z" & int_LastRow).Insert shift:=xlDown

    '[Set Cell Ranges]
    Select Case Specific_Tbl
        Case 1
            '[Remerge Description]
            .Range(.Cells(int_LastRow, "E"), .Cells(int_LastRow, "H")).MergeCells = True
            Set rng_Tmp1 = .Range("B" & int_LastRow & ":C" & int_LastRow)
            Set rng_Tmp2 = .Range("B" & int_LastRow + 1 & ":C" & int_LastRow + 1)
            Set rng_Tmp3 = .Range("E" & int_LastRow & ":J" & int_LastRow)
            Set rng_Tmp4 = .Range("E" & int_LastRow + 1 & ":J" & int_LastRow + 1)
        Case 2, 3
            Set rng_Tmp1 = .Range("B" & int_LastRow & ":C" & int_LastRow)
            Set rng_Tmp2 = .Range("B" & int_LastRow + 1 & ":C" & int_LastRow + 1)
            Set rng_Tmp3 = .Range("E" & int_LastRow & ":F" & int_LastRow)
            Set rng_Tmp4 = .Range("E" & int_LastRow + 1 & ":F" & int_LastRow + 1)
    End Select

    '[Transfer values and clear]
    rng_Tmp1.Value = rng_Tmp2.Value
    rng_Tmp3.Value = rng_Tmp4.Value
    rng_Tmp2.ClearContents
    rng_Tmp4.ClearContents