VBA,搜索具有特定值的行号

时间:2017-06-23 19:30:53

标签: vba excel-vba excel

我是VBA的新手,我想问一下代码有什么问题,我想获取所有行号并将其存储为数组。该行具有特定要求,在每行中,第一个单元格的第一个字母开头 " B"

Sub rowNum()
    Dim rowNum() As Variant
    Dim wbBook As Workbook
    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim row As Integer
    Dim Counter As Integer
    Counter = 0
Set wbBook = ThisWorkbook
    With Workbook
        Set wsSource = .Worksheets("Sheet1")
        Set wsTarget = .Worksheets("sheet2")
    End With
    With wsSource
        Set row = .Range("A1", .Range("A1").End(xlUp)).Count
    End With
    ReDim rowNum(1 To rowN)
For Each c In wsSource.Range("A1:A" & rowN).Cells
If Left(c.Text, 1) = "B" Then Counter = Counter + 1
rowNum(Counter) = c.row
End If

End Sub

1 个答案:

答案 0 :(得分:1)

要一个包含所有行的数组,其中第一个单元格中的值以" B"开头。你可以使用像这样的子

Option Explicit

Public Sub GetRows()
    Dim colA As Variant, rowArr() As Long, ub As Long, i As Long, j As Long, val As String

    colA = Sheet1.UsedRange.Columns("A").Value2

    ub = UBound(colA)
    ReDim rowArr(1 To ub)

    j = 1
    For i = 1 To ub
        val = Trim(colA(i, 1))
        If Len(val) > 0 Then
            'to ignore case use: If LCase(Left(val, 1)) = "b" Then
            If Left(val, 1) = "B" Then
                rowArr(j) = i
                j = j + 1
            End If
        End If
    Next
    ReDim Preserve rowArr(1 To j - 1)
End Sub

您的代码存在的问题:

    应始终在模块顶部使用
  • Option Explicit - 仅此语句可帮助您找到几个问题
  • Dim rowNum() As Variant是一个变种数组,当需要的只是一个Longs数组时
  • Dim row As Integer - 这会隐藏内置函数Range().Row
    • 导致此行出现问题:rowNum(Counter) = c.row
    • 此外,所有Integer数据类型都应替换为Long
  • With Workbook - "工作簿"不是有效的对象
    • 有效对象:"工作簿(i)" (打开文件的集合)," ActiveWorkbook"," ThisWorkbook"
  • Set row = ...无效,因为row被定义为整数
    • 对于像Byte,Integer,Long这样的基本数据类型,您可以直接指定值:val = 1
    • 对象类型(如工作簿,表格,范围,集合)需要
    • Set
  • .Range("A1", .Range("A1").End(xlUp)).Count不会返回已使用的总行数
    • .Range("A1").End(xlUp)表示A1是活动单元格,.End(xlUp)就像按向上箭头一样,结果是活动单元格仍为A1
    • 转换为.Range("A1", "A1").Count - > .Range(Row 1, Col 1).Count - > 1
    • 要查找A列中的最后一行,请使用Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
    • Sheet1.Rows.Count是工作表上的最后一行(100万+)
    • 所以来自Cells(行= 1048576,Col =" A")按向上箭头以转到带有数据的最后一个单元格
  • 正如评论rowN中指出的那样,未声明,也未初始化
    • ReDim rowNum(1 To rowN)失败,因为rowN被隐式创建为空变体
  • 未宣布
  • c
  • For循环未关闭(Next缺失)
  • 这样写的If语句只会执行Counter = Counter + 1
    • If语句有两种形式:
      1. 一行:If 1 = 1 Then "single statement" Else "other single line"(否End If
      2. 或每个分支的语句块,全部在不同的行上,由End If关闭:
If 1 = 1 Then
    statement 1
    statement 2
    etc
Else
    statement 3
    statement 4
    etc
End If