VBA - 谁能解释为什么我用Cells()得到对象错误?

时间:2014-02-07 02:22:11

标签: excel vba excel-vba excel-2013

所有,我很难理解为什么我会遇到对象错误。每当我读到某些内容时,我想我已经弄明白了,当我尝试实现时,我得到了一个错误。我正在使用的特定代码是:

'Set station cell value
iRow = rEmptyStation.Row
iColumn = rEmptyStation.Column
Cells(iRow - 1, iColumn).Copy
Range(Cells(iRow, iColumn), Cells(iRow, iColumn)).Select
Selection.Paste
rEmptyStation.Value = sStation

iRowiColumn类型为long,rEmptyStation是范围,sStation是字符串。我要做的就是将单元格复制到相关单元格上方,将其粘贴到相关单元格(对于它的格式化),然后将相关单元格设置为等于字符串。

它在我有[junk].Select的行上给了我一个对象错误。代替[junk],我尝试了Cells(iRow, iColumn),我尝试使用With Worksheets(1).Cells(iRow, iColumn)语句,我也尝试使用.Cells().Range()声明中的With

任何人都可以向我解释如何让它工作,以及如何在每种情况下选择正确的代码????

3 个答案:

答案 0 :(得分:2)

我无法确定为什么它无法正常工作,因为我无法看到您的数据 可能的原因是iRow的值是否为1 Excel无法评估Cells(0,iColumn)

你可以试试这个:

If iRow <> 1 Then: _
Cells(iRow - 1, iColumn).Copy Cells(iRow, iColumn) '~~> Direct copy
rEmptyStation.Value = sStation

或者如果您只想复制Cell以上rEmptyStation的格式,那么:

If rEmptyStation.Row <> 1 Then
    rEmptyStation(-1).Copy
    rEmptyStation.PasteSpecial xlPasteFormats '~~> Direct copy and paste formats
    rEmptyStation.Value = sStation
End If
Application.CutCopyMode = False

希望这有帮助。

答案 1 :(得分:0)

以下代码适用于我:

Sub Test()

    Dim sStation As String
    Dim rEmptyStation As Range
    Dim selectedCell As Range
    Dim iRow As Integer
    Dim iColumn As Integer

    sStation = "Test"
    Set rEmptyStation = Range("A2")

    'Set station cell value
    iRow = rEmptyStation.Row
    iColumn = rEmptyStation.Column
    Cells(iRow - 1, iColumn).Copy
    Set selectedCell = Range(Cells(iRow, iColumn), Cells(iRow, iColumn))
    selectedCell.PasteSpecial
    rEmptyStation.Value = sStation

End Sub

如果您将字符串'Original'放在A1中,它将被复制到单元格A2中,然后A2中的文本将替换为'Test'。

答案 2 :(得分:0)

最终为我工作的是将我的代码转换为以下内容:

'Set station cell value
iRow = rEmptyStation.Row
iColumn = rEmptyStation.Column
Cells(iRow - 1, iColumn).Copy
Cells(iRow, iColumn).Select
Selection.PasteSpecial xlPasteFormats
rEmptyStation.Value = sStation

现在,我不知道为什么,但是当我得到以下代码时,我得到了对象错误(在Selection.Paste行):

'Set station cell value
iRow = rEmptyStation.Row
iColumn = rEmptyStation.Column
Cells(iRow - 1, iColumn).Copy
Cells(iRow, iColumn).Select
Selection.Paste
rEmptyStation.Value = sStation

这是我项目的a link。如果有人能弄清楚这一点,那就太好了(有问题的代码段之后的代码没有被测试!)。