[英]How to set a new range variable to one cell address
我有下面的代码(几乎)
Sub Find_PhaseCode_Cell2()
Dim rng As Range
Dim newrng As Range
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = Sheets("Control budget ")
With ws
Set rng = Range("b57:b64")
With rng
For x = 57 To 64
If Cells(x, 2).Value <> "" Then
Debug.Print Cells(x, 2).Address
End If
Next x
End With
End With
End Sub
debug.print 语句在哪里,我希望它是变量newrng 。
如果我尝试设置该set newrng = Cells(x,2).address
,则会出现错误:
所需对象
我究竟做错了什么?
你不需要.address
。 所有你需要的是: Set newrng = Cells(x, 2)
它位于“With”语句中,因此您应该通过前缀“.”来引用成员。
也不要忘记使用直接引用(即 wb.Worksheets)
以下应该是您的示例...
Sub Find_PhaseCode_Cell2()
Dim rng As Range
Dim newrng As Range
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Control budget ")
With ws.Range("B57:B64")
For x = 57 To 64
If .Cells(x, 2).Value <> "" Then
Set newrng = .Cells(x, 2)
Debug.Print newrng.Address
End If
Next x
End With
End Sub
所以修复不是将 newrng 声明为一个范围。 我把它作为一个变体,下面的代码现在可以工作了。
Sub Find_PhaseCode_Cell2()
Dim rng As Range
Dim newrng
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = Sheets("Control budget ")
With ws
Set rng = Range("b57:b64")
With rng
For x = 57 To 64
If Cells(x, 2).Value <> "" Then
Debug.Print Cells(x, 2).Address
newrng = Cells(x, 2).Address
MsgBox newrng
End If
Next x
End With
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.