【问题标题】:Checking if there is any data entered into a range of cells using VBA in Excel在 Excel 中使用 VBA 检查是否有任何数据输入到单元格区域中
【发布时间】:2016-07-11 18:07:54
【问题描述】:

当第一个空行(减去最后一列)被填充时,我试图调用 Sub (New_Row)。我在如何在最后的 If 语句中引用一系列单元格时遇到问题。

Sub Data_Added()
'Check if anything has been entered into the first empty row in "Data"

     Dim sht As Worksheet
     Dim LastRow As Long
     Dim LastColumn As Long
     Dim StartCell As Range

     Sheets("Data").Select
     Set sht = Worksheets("Data")
     Set StartCell = Range("A1").End(xlDown).Select

     Worksheets("Data").UsedRange

     LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
     LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column

     Set InputRange = sht.Range(StartCell, sht.Cells(LastRow + 1, LastColumn - 1))

     If InputRange Is Not Nothing Then
          Call New_Row
     End If
End Sub

我见过有人使用 Application.Intersect 方法,但我不确定相交是否只对一行单元格有意义。不过,对 VBA 来说是全新的,所以我不知道。现在我收到一个“无效使用对象”错误,指向 If 语句中的“无”。

【问题讨论】:

  • 请参阅here,了解在范围/工作表/等中查找“最后一个”单元格的更好方法。
  • 除了@DavidZemens 写的,IF 语句的正确语法是If Not InputRange is Nothing Then

标签: vba excel


【解决方案1】:
Dim y As Long, lastx As Long
Dim sht As Worksheet

y = 1  'Row you want to check

Set sht = ThisWorkbook.Worksheets("Sheet1")
lastx = sht.Cells(y, sht.Columns.Count).End(xlToRight).Column - 1

If WorksheetFunction.CountA(Range(Cells(y, 1), Cells(y, lastx))) <> 0 Then      'Call New_Row when the row you are checking is empty
    Call New_Row
End If

你尝试过这样的事情吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多