我是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
答案 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
With Workbook
- "工作簿"不是有效的对象
Set row = ...
无效,因为row
被定义为整数
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
Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
Sheet1.Rows.Count
是工作表上的最后一行(100万+)rowN
中指出的那样,未声明,也未初始化
ReDim rowNum(1 To rowN)
失败,因为rowN
被隐式创建为空变体c
For
循环未关闭(Next
缺失)Counter = Counter + 1
行
If 1 = 1 Then "single statement" Else "other single line"
(否End If
)End If
关闭:If 1 = 1 Then statement 1 statement 2 etc Else statement 3 statement 4 etc End If