我是VBA的新手,正在尝试编写一个简单的代码来标识单个数据块的第一行,最后一行,第一列和最后一列。
我在工作表中有多个数据块,这些数据块是模板形式的,但它们是动态的,并且数据块中的行可能每次(或报告期)都在不断变化。
第一个数据块的范围是B2:E10
第二个数据块的范围是B13:F29
第三数据块的范围是B32:H35
我编写了以下代码来测试是否可以选择从特定单元格到第一个数据块的最后一行和最后一列的数据范围,但是它选择了整个数据 `if(empty($Category)){
echo "Field must be filled out";
header('Location: dashboard.php');
exit;`
。
(B2:I35)
我想先选择Private Sub RangeIdentification()
Dim Dsheet As Worksheet
Dim rng1 As Range, rng2 As Range, rng3 As Range
Dim firstrow1 As Long, firstrow2 As Long, firstrow3 As Long
Dim lastrow1 As Long, lastrow2 As Long, lastrow3 As Long
Dim lastcol1 As Long, endcol2 As Long, finalcol3 As Long
Set Dsheet = Worksheets("Data")
lastrow1 = Dsheet.Cells(Rows.Count, 2).End(xlUp).Row
lastcol1 = Dsheet.Cells(2, Columns.Count).End(xlToLeft).Column
Set rng1 = Dsheet.Cells(2, 2).Resize(lastrow1 - 1, lastcol1)
rng1.Select
End Sub
,然后选择B2:E10
,最后选择B13:F29
。
答案 0 :(得分:0)
可以这样尝试,将选择B列中的所有数据块(不包括它们之间的空白)
Sub test()
Dim Dsheet As Worksheet, Rng As Range, NextRow As Long
Dim TRng As Range
Set Dsheet = ThisWorkbook.Sheets("Data")
Set Rng = Dsheet.Cells(Rows.Count, "B").End(xlUp).CurrentRegion
Set TRng = Rng
Do
NextRow = Rng(1, 2).End(xlUp).Row
If NextRow = 1 Then Exit Do
Set Rng = Dsheet.Cells(NextRow, "B").CurrentRegion
Set TRng = Union(TRng, Rng)
Loop
If Not TRng Is Nothing Then TRng.Select
End Sub