VBA – 任何人都可以解释为什么我与细胞()的对象错误?
所有的,我很难理解为什么我得到对象的错误。 每次我读了一些东西,我想我已经想通了,当我尝试实现时,我得到一个错误。 我正在使用的特定代码是:
'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
iRow
和iColumn
的types是long, rEmptyStation
是一个范围, sStation
是一个string。 我想要做的就是复制单元格上方的单元格,将其粘贴到单元格(正在格式化),然后将单元格设置为等于string。
它给了我一个对象的错误,我有[junk].Select
的路线。select。 我试过把Cells(iRow, iColumn)
,我试过使用With Worksheets(1)
和.Cells(iRow, iColumn)
语句,我也试过使用.Cells()
和.Range()
在With
语句中。
任何人都可以向我解释如何得到这个工作,以及如何在任何情况下select正确的代码?
我真的不知道为什么它不工作,因为我看不到你的数据
可能的原因是iRow
值是1。
Excel无法评估Cells(0,iColumn)
。
你可以试试这个:
If iRow <> 1 Then: _ Cells(iRow - 1, iColumn).Copy Cells(iRow, iColumn) '~~> Direct copy rEmptyStation.Value = sStation
或者如果您只想复制rEmptyStation
上方的Cell
格式,则:
If rEmptyStation.Row <> 1 Then rEmptyStation(-1).Copy rEmptyStation.PasteSpecial xlPasteFormats '~~> Direct copy and paste formats rEmptyStation.Value = sStation End If Application.CutCopyMode = False
希望这可以帮助。
以下代码适用于我:
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
如果在A1中放置string“Original”,则将其复制到单元格A2中,然后将A2中的文本replace为“Test”。
最后为我工作的是将我的代码切换到以下内容:
'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
这是一个完整的项目链接 。 如果任何人都可以弄清楚,那就太好了(这个片段之后的代码没有被testing过!)。