我下面的代码几乎可以正常工作
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
,则会出现错误
需要对象
我在做什么错了?
答案 0 :(得分:2)
您不需要.address
。您所需要做的就是:Set newrng = Cells(x, 2)
答案 1 :(得分:0)
它在'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
答案 2 :(得分:0)
所以解决方法不是将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
感谢您的所有帮助。