运行时错误1004-Excel宏-代码之前运行得很好

时间:2018-08-15 07:18:51

标签: excel vba excel-vba

我有以下代码在表的最后一行之后插入新行。

Private Sub CommandButton1_Click()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer, additionalRow As Integer, additionalRowCounter As Integer, offsetRowCounter As Integer
    Dim currentRowValue As String
    'Dim Step5 As Range
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("2.Set Up")

    ws.Activate
    sourceCol = 3   'Entity Name is column C, which has a value of 6
    additionalRow = 0
    offsetRowCounter = 0
    rowCount = ws.Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row starting from 4th row, find the first blank cell and select it
    For currentRow = 4 To rowCount
        currentRowValue = ws.Range(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Rows(currentRow).Insert shift:=xlShiftDown
            Exit For
        End If
        additionalRow = additionalRow + 1
   Next
End Sub

表从C4开始。

以前效果不错,但是从昨天开始我就得到了

  

在编译代码时出现运行时错误1004。

我在工作表上没有做任何更改。

请提示可能是什么问题

1 个答案:

答案 0 :(得分:1)

您正在使用Index数字来引用单元格,但同时您想使用Range表示法来获取值。因此,更改此行:

currentRowValue = ws.Range(currentRow, sourceCol).Value

收件人:

currentRowValue = ws.cells(currentRow, sourceCol).Value

想知道 more 吗?