在列中找到下一个空单元格时避免合并单元格

时间:2013-07-11 17:28:59

标签: vba excel-vba excel

我有一个打开文档的宏,复制某列中的最后一行并将该值粘贴到我遇到问题的另一个工作簿中的下一个空单元格中。这在以前工作过,但在这个特定的文档中,第一行包含合并和居中的单元格,包括列(B),我想找到下一个空单元格并粘贴该值。当我运行代码时得到“此操作需要合并的单元格大小相同”的消息。在下面的代码中,我尝试将rowToPaste更改为2(绕过包含合并单元格的第一行),这会崩溃excel。如何在检查第一个空单元格时找到宏绕过第一行,或者找到另一种方法来避免同样大小的合并单元格问题?提前谢谢。

Private Sub CommandButton1_Click()
Dim NextRow As Long, LastRow As Long
Dim vMax As Variant
Dim rowToPaste As Integer
Dim lastRowToPaste As Integer
Dim lastCheckedRow As Integer

Set wsMaster = ThisWorkbook.Sheets("FY 13 Budgets -- East Coast")
NextRow = wsMaster.Range("A" & Rows.Count).End(xlUp).Row + 1

Set wbDATA = Workbooks.Open("C:\Documents and Settings\Michael Palkovitz\My Documents\Test\PDF to excel.xlsm")
With wbDATA.Sheets("8A")
    LastRow = .Range("B" & .Rows.Count).End(xlUp).Row

    If LastRow > 1 Then
        .Range("B" & LastRow).Copy
        lastRowToPaste = LastRow + 1000
        rowToPaste = lastCheckedRow
        Do
           rowToPaste = rowToPaste + 1
           If IsEmpty(wsMaster.Range("B" & rowToPaste)) Then
               wsMaster.Range("B" & rowToPaste).PasteSpecial xlPasteValues
               wsMaster.Range("B" & rowToPaste).PasteSpecial xlPasteFormats
               lastCheckedRow = rowToPaste
               Exit Do
           End If
        Loop While (rowToPaste < lastRowToPaste)
    End If
End With

wbDATA.Close False
End Sub

1 个答案:

答案 0 :(得分:0)

我开始回复您对您的问题的评论,但认为这将更容易作为答案阅读。

有一些事情需要清理或澄清。

  1. 始终要求变量声明。未声明wsMasterwbData。在VBE中,转到工具 - &gt;设置此选项。
  2. 您将某些行变量声明为整数,将其他变量声明为long。始终使用long来避免溢出错误。
  3. 您将lastRowToPaste设置为大于LastRow的1000。 1000的意义是什么?
  4. NextRowLastRow首字母大写。所有其他变量都有一个小写的首字母。您应该使用一致的命名约定。
  5. NextRow的目的是什么?您设置其值,然后再也不使用它。
  6. 您将rowToPaste设置为lastCheckedRow,这是一个尚未初始化的变量。它的默认值是0,所以rowToPaste是0.在你Do...Loop的第一次迭代中,你将rowToPaste递增1,所以第一次通过,它等于1,这是你的错误的原因
  7. 为了解决这个问题,请对代码进行以下更改:

    更改

    rowToPaste = lastCheckedRow
    

    到此:

    rowToPaste = 2
    

    并在循环结束时增加rowToPaste而不是开头:

        ...
        End If
        rowToPaste = rowToPaste + 1
    Loop While (rowToPaste < lastRowToPaste)
    
相关问题