您好我在尝试根据"A2:H2"
选择范围column A
到最后一个填充的单元格(因此在这种情况下应选择"A2:H59"
)。范围不固定,因此无法使用确切的数字定义。我有以下代码,但它会选择所有内容到第402行,即使表单中没有"A59"
之外的数据。知道发生了什么事吗?谢谢你的帮助!
Global ssaw As Worksheet
Global trckr As Worksheet
Sub DataF()
Dim myRange As Range
Dim myCell As Range
Set ssaw = Sheets("SSAW_DATA")
Set trckr = Sheets("SQL_DATA_FEED")
Set myRange = trckr.Range("A2:H2").end(xlDown)
With myRange
.SpecialCells(xlCellTypeBlanks).Interior.Color = RGB(255, 102, 102)
.SpecialCells(xlCellTypeBlanks).Value = "#missing#"
End With
End Sub
答案 0 :(得分:2)
如果我们假设A列中最后一个使用的单元格为A59
,那么......
......这个
Set myRange = trckr.Range("A2", trckr.Range("A2").End(xlDown))
将选择A2:A59
和此
.Resize(ColumnSize:=8)
会调整它的大小,使其为8列宽A2:H59
。
我们一起得到:
Set myRange = trckr.Range("A2", trckr.Range("A2").End(xlDown)).Resize(ColumnSize:=8)
使用此
trckr.Range("A" & trckr.Rows.Count).End(xlUp)
或者,如果中间可能有空单元格,则找到A列中最后使用过的单元格:
Set myRange = trckr.Range("A2", trckr.Range("A" & trckr.Rows.Count).End(xlUp)).Resize(ColumnSize:=8)
答案 1 :(得分:2)
利用Range(cell1, cell2)
等同于Range(cell2, cell1)
Set myRange = trckr.Range("H2", trckr.Range("A2").End(xlDown))
如果你想选择一个范围从A2:H2到A列最后一个非空单元格(即在第一个和最后一个非空单元格之间沿A列包含空单元格):
Set myRange = trckr.Range("H2", trckr.Cells(trckr.Rows.Count, 1).End(xlUp))
答案 2 :(得分:1)
我建议使用以下代码
Option Explicit
Function LastRowInColumn(colName As String)
Dim lastRow As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, colName).End(xlUp).Row
End With
LastRowInColumn = lastRow
End Function
Sub SelectRg()
Dim rg As Range
Dim wks As Worksheet
Dim lastRow As Long
lastRow = LastRowInColumn("A")
Debug.Print lastRow
If lastRow = 1 Then
' do nothing
Else
Set wks = ActiveSheet
With wks
Set rg = Range(.Cells(2, 1), .Cells(lastRow, "H"))
rg.Select
End With
End If
End Sub
代码确定A列中最后一个填充的行,并根据此信息选择所有内容到列H
编辑改进功能
Function LastRowInColumn(ByVal wks As Worksheet, ByVal colName As String) As Long
With wks
LastRowInColumn = .Cells(.Rows.Count, colName).End(xlUp).Row
End With
End Function
EDIT2 如果你不想使用额外的功能你就可以这样做
Sub SetRg()
Dim rg As Range
Dim wks As Worksheet
Dim lastRow As Long
Set wks = ActiveSheet
With wks
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'lastRow = LastRowInColumn(wks, "A")
If lastRow > 1 Then
Set rg = Range(.Cells(2, 1), .Cells(lastRow, "H"))
End If
End With
End Sub