2017-01-11 88 views
0

中插入值,當我得到運行時錯誤「1004」Excel的VBA - 錯誤「1004」的最後一個非空行

應用程序定義或對象定義的錯誤

當我」 m嘗試從B19開始插入值。

下面是代碼:

Private Sub test() 

If Application.CountIf(Sheets("Sheet1").Columns(2), Range("A5").Value) Then 
    MsgBox "Already taken, try another username" 
Else 
    MsgBox "Done" 
    Sheets("Sheet1").Range("B19" & Rows.Count).End(xlUp).Offset(1, 0) = Range("A5").Value 

End If 

End Sub 

這段代碼的目的是從A5插入值到最後一個非空行從B19開始。

+1

您的地址:'( 「B19」 和Rows.Count)'解析爲'B191048576',這是一個非法地址。因此錯誤。 B列中的最後一個空單元格將由'cells(rows.Count,「B」)返回。end(xlup).offset(1,0)'**但是**您必須專門測試'B19'不是空的,如果你想從'B19'開始 –

回答

0

你可以試試這個:

Private Sub main() 
    With Sheets("Sheet1") 
     With .Range("B19:B" & WorksheetFunction.Max(.Cells(.Rows.Count, 2).End(xlUp).Row, 19)) 
      If Application.CountIf(.Cells, .Parent.Range("A5").Value) > 0 Then 
       MsgBox "Already taken, try another username" 
      Else 
       .Cells(.Rows.Count + IIf(IsEmpty(.Cells(.Rows.Count)), 0, 1)).Value = .Parent.Range("A5").Value 
       MsgBox "Done" 
      End If 
     End With 
    End With 
End Sub 
+0

你是一個救生員..謝謝 – Jeeva

+0

不客氣 – user3598756

+0

我實現了代碼修改如下: 將「B19:B」更改爲「L19:L」並將A5更改爲B24。但是它開始從第47行鍵入。 – Jeeva

0

2評論:

第一:CountIf返回一個數字,所以如果有ATLEAST一個計數,你應該檢查,如果結果是> 0(如果沒有True)。

第二種:在範圍(「B19」)之後進入數據的最後一行,您需要使用.Range("B" & .Rows.Count).End(xlUp).Offset(1, 0)

嘗試下面的代碼:

Private Sub test() 

With Sheets("Sheet1") 
    If Application.CountIf(.Columns(2), .Range("A5").Value) > 0 Then 
     MsgBox "Already taken, try another username" 
    Else 
     If .Cells(.Rows.Count, "B").End(xlUp).Row < 19 Then ' <-- check if the last row in Column B is less than 19 
      .Range("B19").Value = .Range("A5").Value 
     Else 
      .Range("B" & .Rows.Count).End(xlUp).Offset(1, 0).Value = .Range("A5").Value 
     End If 

     MsgBox "Done"   
    End If 
End With 

End Sub 
+0

如果在列B中沒有值,這將是錯誤的。在這種情況下,OP想要將值寫入B19。 – Vityata

+0

我不確定你是對的,因爲我知道他很可能有數據上傳到「B19」,這就是爲什麼他想找到數據的最後一行(在「B19」之後),並將「A5」放入第一個空行(我可能是錯的 - PO會解釋得更好) –

+0

您仍然可以從B19開始,無論他是否擁有數據。 – Vityata