无法定义获取第一个空白单元格的范围

时间:2018-06-17 12:35:06

标签: vba excel-vba excel

我有两个vba项目,一个用于员工,另一个用于产品。

第一个工作正常,所以我从员工处获得了用于产品的代码。

问题是这部分代码在员工vba项目和产品中运行良好,我收到424对象是必需的错误:

 ThisWorkbook.Worksheets("Plan1").Activate

    Dim ID As Long

    With Plan1
    ID = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    .Range("A" & ID) = ID - 1
    txtbox1 = Cells(ID, 1)
    End With
你能帮我吗?我尝试了一切,但它似乎是一个excel bug,因为我无法弄清楚它发生了什么。

我已经感谢你的帮助了。

2 个答案:

答案 0 :(得分:0)

尝试,

Dim ID As Long

with ThisWorkbook.Worksheets("Plan1")
    ID = .Range("A" & .Rows.Count).End(xlUp).Row + 1)
    .Range("A" & ID) = ID - 1
     txtbox1 = .Cells(ID, 1)
End With

使用...结束使用块,。范围和。细胞成为thisWorkbook.Worksheets(" Plan1")。范​​围(...)和thisWorkbook.Worksheets(" Plan1&# 34。)细胞(...)。这并不意味着您可以随意使用Plan1作为工作表对象。

答案 1 :(得分:0)

你有办法

利用Activate并依赖当前 Active 表:

ThisWorkbook.Worksheets("Plan1").Activate

Dim ID As Long

ID = Range("A" & Rows.Count).End(xlUp).row + 1 
Range("A" & ID) = ID - 1
txtbox1 = cells(ID, 1)

或者将Plan1定义为Worksheet对象并使用它:

Dim Plan1 As Worksheet
Set Plan1 = ThisWorkbook.Worksheets("Plan1") ' set your worksheet object

Dim ID As Long

With Plan1
    ID = .Range("A" & .Rows.Count).End(xlUp).row + 1
    .Range("A" & ID) = ID - 1
    txtbox1 = .cells(ID, 1)
End With

关于后一种选择,您可以采用With ... End With方法:

Dim Plan1 As Worksheet
Set Plan1 = ThisWorkbook.Worksheets("Plan1") ' set your worksheet object

With Plan1 ' reference your sheet
    With .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0) ' reference its column A first empty cell after last not empty one
        .Value = .row - 1 ' set referenced cell value as its row index minus one
        txtbox1 = .Value ' set some 'txtbox' object default property to referenced cell value
    End With
End With