Excel VBA使用空列A填充第一个空白行与第一行

时间:2017-04-21 00:26:14

标签: excel vba excel-vba

我有这段代码来选择要填充的第一个空行

Set myData = Workbooks.Open("C:\Users\Charles\Desktop\WFACS - Work Order System\Work Order Management System.xlsm")
Worksheets("Sheet5").Select
Worksheets("Sheet5").Range("A3").Select
RowCount = Worksheets("Sheet5").Range("A3").CurrentRegion.Rows.Count
With Worksheets("Sheet5").Range("A2")
    .Offset(RowCount, 0) = TaskType
    .Offset(RowCount, 1) = TimeSensitive
    .Offset(RowCount, 2) = TimeSensitiveDate
    .Offset(RowCount, 3) = TodaysDate
    .Offset(RowCount, 4) = Address
    .Offset(RowCount, 5) = Location
    .Offset(RowCount, 6) = Department
    .Offset(RowCount, 7) = ContactName
    .Offset(RowCount, 8) = ContactEmail
    .Offset(RowCount, 9) = Description

我想更改它以使用此代码填充列A为空的第一行:

Range("A1").End(xlDown).Offset(1, 0).Select

但每次我把它放入代码中我都会遇到运行时错误(9):下标超出范围。

有人可以帮我把这两个放在一起,我知道这里有其他线程可以讨论这个问题,但没有任何东西可以帮我解决这个特殊的错误。

1 个答案:

答案 0 :(得分:2)

假设您的工作表在单元格A1和A2中有某些内容,则以下代码应该起作用:

Set myData = Workbooks.Open("C:\Users\Charles\Desktop\WFACS - Work Order System\Work Order Management System.xlsm")
With myData.Worksheets("Sheet5").Range("A1").End(xlDown).Offset(1, 0).EntireRow
    .Cells(1, "A").Value = TaskType
    .Cells(1, "B").Value = TimeSensitive
    .Cells(1, "C").Value = TimeSensitiveDate
    .Cells(1, "D").Value = TodaysDate
    .Cells(1, "E").Value = Address
    .Cells(1, "F").Value = Location
    .Cells(1, "G").Value = Department
    .Cells(1, "H").Value = ContactName
    .Cells(1, "I").Value = ContactEmail
    .Cells(1, "J").Value = Description
End With

这可以避免任何Select语句。

如果您在单元格A2中没有任何数据,那么最好使用:

With myData.Worksheets("Sheet5").Cells(myData.Worksheets("Sheet5").Rows.Count, "A").End(xlUp).Offset(1, 0).EntireRow

从底部开始工作并向上搜索以找到最后使用过的单元格。 (但是没有处理最后一个非空单元格上面有空单元格的情况。)

编辑(对于"高级用户"):

正如A.S.H在评论中指出的那样,可以通过以下方式完成:

Set myData = Workbooks.Open("C:\Users\Charles\Desktop\WFACS - Work Order System\Work Order Management System.xlsm")
myData.Worksheets("Sheet5").Range("A1").End(xlDown).Offset(1, 0).Resize(, 10).Value = Array( _
              TaskType, _
              TimeSensitive, _
              TimeSensitiveDate, _
              TodaysDate, _
              Address, _
              Location, _
              Department, _
              ContactName, _
              ContactEmail, _
              Description)