2014-02-07 29 views
0

所有的,我很難理解爲什麼我收到對象錯誤。每次我讀了一些東西,我想我已經想通了,當我嘗試實現時,我得到一個錯誤。我現在有工作的特定代碼:VBA - 任何人都可以解釋爲什麼我使用Cells()獲得對象錯誤?

'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是長型的,rEmptyStation是一個範圍,sStation是一個字符串。我想要做的就是複製單元格上方的單元格,將其粘貼到單元格中(爲了格式化),然後將單元格設置爲與字符串相同。

它給我的,我有[junk].Select線的對象錯誤。代替[junk],我試過把Cells(iRow, iColumn),我試過使用With Worksheets(1).Cells(iRow, iColumn)聲明,並且我也嘗試在With聲明中使用.Cells().Range()

誰能向我解釋如何得到這個工作,以及如何選擇在任何情況下正確的代碼????

回答

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我的全部項目。如果任何人都可以弄清楚,那就太好了(這個片段之後的代碼沒有被測試過!)。

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 

如果你把字符串「原始」的A1,它被複制到單元格A2,然後在A2文本替換爲「測試」。

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 

希望這有助於。

+0

爲'rEmptyStation是Nothing'的情況下,它不設置也許增加一個測試。這很可能是答案,但OP沒有提供反饋意見。 –

+0

當我的代碼運行時,iRow和iColumn不是1或0.另外,在上面的代碼中,我有'如果rEmptyStation是Nothing Then',所以它不是那樣。截至目前,我的代碼分別生成6和13的iRow和iColumn。我現在要記錄一個宏,看它是否給了我一些東西,但由於我指的是從一個範圍中找到的行和列,我不知道它是否有用。 – user3282106

+0

@chrisneilsen另外,我正在家裏的空閒時間工作,所以我不會超級致力於此。 – user3282106

相關問題