RowNum的变量,用于列中第一个和最后一个整数,并在2之间创建范围

时间:2017-06-07 12:43:07

标签: excel vba excel-vba

我想创建两个变量,一个用于J列中第一个整数的行号,另一个用于J列中的最后一个整数(此后有很多行#N A N A)。然后,我想使用这两个点为列J创建一个范围,但也为列D创建一个范围(使用相同的变量) 本周早些时候我刚开始使用vba,了解简单性,我在其他地方找到了类似的答案,但没有一个具体。任何帮助将非常感激。到目前为止我所拥有的:

Dim StartRow As Integer
Dim sht As Worksheet
Dim LastRow As Integer
Dim JRange As Range
Dim DRange As Range

Set StartRow = Range("j7:j100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
LastNonRow = sht.Cells(sht.Rows.Count, 8).End(xlUp).Row (I fear this includes the #N A N A rows too)

Set JRange = sht.Range(StartRow,10,sht.Cells(LastRow,10))
Set DRange = sht.Range(StartRow,4,sht.Cells(LastRow,4))

2 个答案:

答案 0 :(得分:0)

首先,你应该使用:

Set JRange = sht.Range(sht.Cells(StartRow,10),sht.Cells(LastRow,10))

其次,请勿将Set关键字与Integer或其他值类型一起使用。 Set关键字仅用于对象。如果您不熟悉对象与值类型,则应对此进行一些研究。以下是一些Excel VBA示例:

Dim i     As Integer
Dim j     As Double
dim str   as String
Dim coll  As Collection
dim sht   As Worksheet
dim rng   As Range

i = 1
j = 2.4
str = "This is a string of text, also a value type"
Set coll = ThisWorkbook.Sheets    'Note that ThisWorkbook.Sheets is a Collection
Set sht = coll(1)    'sets sht to the first Sheet in coll
Set rng = sht.Range("A1")

如果您只关心数字是否在单元格中而不一定是整数,您可以这样做

'Use Double instead of Integer because the possible range of values is larger. 
'This reduces risk of error
Dim LastRow     As Double  
Dim UpperLimit  As Double 

'Assuming you already have StartRow
LastRow = StartRow + 1

'Use UpperLimit to ensure you don't go into an infinite loop
'Set UpperLimit to an appropriately high value
UpperLimit = 100000

'Test Loop
Do While IsNumeric(sht.Cells(LastRow,10).Value) and LastRow <= UpperLimit
    LastRow = LastRow + 1
Loop

'Check if it exceeded upper limit
If LastRow > UpperLimit Then
    MsgBox "Exceeded Limit"
    Exit Sub
End If

LastRow = LastRow - 1    'Because the sht.Cells(LastRow,10).value is non-numeric

'Now set ranges

如果你关心它是否实际上是一个整数,你可以使用上面的代码,但在循环中放入一个条件语句来测试这个数字是否确实是一个整数。 Web上有许多资源可以提供用于确定值是否为整数的代码。

此外,您应该确保在使用之前设置sht变量。

Set sht = ThisWorkbook.Sheets(1)

或者

Set sht = ThisWorkbook.Sheets("MySheetName")

希望这有帮助。

编辑: 如果范围与整数不连续,则反转循环:

LastRow = UpperLimit
Do Until IsNumeric(sht.Cells(lastRow,10).Value)) Or LastRow = StartRow
    LastRow = LastRow - 1
Loop

如果您这样做,请从代码末尾删除LastRow = LastRow-1,因为您要查找的值已经在LastRow中。

答案 1 :(得分:0)

您的代码存在许多问题: Set StartRow - 您只在创建对象时使用Set。 引用单元格也存在问题。有很多不同的方法可以做到这一点,我建议你阅读这篇文章。

以下将使用数字的第一行和带数字的最后一行,即使其间存在非数字值。它将在当前活动的工作表上运行。

Sub test()
Dim StartRow As Integer
Dim LastRow As Integer

Dim JRange As Range
Dim DRange As Range
Dim RangeForLoop As Range

StartRow = Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
For Each RangeForLoop In Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells
    LastRow = RangeForLoop.Row
Next RangeForLoop

Set JRange = Range("J" & StartRow & ":J" & LastRow)
Set DRange = Range("D" & StartRow & ":D" & LastRow)

End Sub