我无法从上一行偏移到最后一行。实际上,我尝试在下面运行我的代码,出现了错误消息
编译错误:无效的限定词...
问题显然来自我的变量lastRow4 = lastRow3.Offset(-1, 0)
当我删除代码的这一行并在VBA代码中将倒数第二行Range("A3:F" & lastRow4).Select
替换为Range("A3:F" & lastRow3).Select
时,我的代码可以工作,但是选择会选择直到lastrow
的范围(在我的代码是lastRow3
),这不是我想要的。
如果有人知道解决方案以解决该问题,以使我的变量lastRow4不向我返回任何错误消息,那就太好了。
非常感谢。 哈维
Sub gdfgdhgf()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer, lastRow3 As Integer, lastRow4 As Integer
Dim currentRowValue As String
sourceCol = 5 'column F has a value of 5
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row 'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
lastRow3 = currentRow
End If
Next
lastRow4 = lastRow3.Offset(-1, 0)
Range("A3:F" & lastRow4).Select
End Sub
答案 0 :(得分:3)
以下不是代码。这是一个例子。修改并尝试:
Option Explicit
Sub test()
Dim LastRow As Long
With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row '<- Get the last row of column A sheet1
'In order to refer to line before Lastrow you can use:
.Range ("A" & LastRow - 1)
End With
End Sub
答案 1 :(得分:3)
尝试以下代码,在代码注释中进行解释:
Option Explicit
Sub gdfgdhgf()
Dim sourceCol As Long, rowCount As Long, currentRow As Long, lastRow3 As Long, lastRow4 As Long
Dim CurrentRng As Range
Dim currentRowValue As String
Dim Sht As Worksheet
Set Sht = ThisWorkbook.Sheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
sourceCol = 5 'column F has a value of 5
With Sht
rowCount = .Cells(.Rows.Count, sourceCol).End(xlUp).Row ' for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
' I think you are trying to set it as a range
Set CurrentRng = .Cells(currentRow, sourceCol)
If IsEmpty(CurrentRng) Or CurrentRng.Value2 = "" Then
lastRow3 = CurrentRng.Row ' get the row of the CurrentRng.Row
End If
Next
lastRow4 = lastRow3 - 1 ' just subtract 1, no need to use Offset
.Range("A3:F" & lastRow4).Select ' <-- Not sure why you need to Select
End With
End Sub