运行时错误“ 1004”对象'_Global失败的方法“ Range”。

时间:2020-09-22 08:23:19

标签: excel vba

'我只想选择5天内属于某个范围(> = 751和<= 1600)的所有单元格。但是我不断收到此运行时错误“ 1004”,对象“ _Global失败”的方法“范围”。任何帮助表示赞赏。

Public Sub tank_2()

Dim t As String
Dim var As Range


Set var = Application.InputBox("enter range", , , , , , , 8)
t = var.Address


For Each cell In Range(t)
    If myrng = Empty And cell >= 751 And cell <= 1600 Then

        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        myrng = myrng & "," & cell.Address(0, 0)
    End If
    
Next cell

For Each cell In Range(t).Offset(0, 18)
    If myrng = Empty And cell >= 751 And cell <= 1600 Then

        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        myrng = myrng & "," & cell.Address(0, 0)
    End If
    
Next cell

For Each cell In Range(t).Offset(0, 36)
    If myrng = Empty And cell >= 751 And cell <= 1600 Then

        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        myrng = myrng & "," & cell.Address(0, 0)
    End If
    
Next cell

For Each cell In Range(t).Offset(0, 54)

    If myrng = Empty And cell >= 751 And cell <= 1600 Then
        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        myrng = myrng & "," & cell.Address(0, 0)
    End If
    
Next cell

For Each cell In Range(t).Offset(0, 72)

    If myrng = Empty And cell >= 751 And cell <= 1600 Then.   
        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        myrng = myrng & "," & cell.Address(0, 0)
    End If
    
Next cell
   
Range(myrng).Select

End Sub

1 个答案:

答案 0 :(得分:0)

您可以将myrng设置为字符串,我们需要确定len(myrng)= 0是否放置“,”。

如果您要选择符合该条件的单元格,则myrng必须正确。

这是当您输入错误的myrng时发生的情况

enter image description here

If myrng=empty,我不确定该怎么做。

这是代码的开头固定的地方,您将必须纠正其余的代码。

Dim t As String, myrng As String
Dim var As Range, x

Set var = Application.InputBox("enter range", , , , , , , 8)
t = var.Address

For Each cell In Range(t)
    x = IIf(Len(myrng) = 0, "", ",")
    If myrng= Empty And cell >= 751 And cell <= 1600 Then
        
        myrng = cell.Address(0, 0)
    ElseIf cell >= 751 And cell <= 1600 Then
        
        myrng = myrng & x & cell.Address(0, 0)
    End If
    
Next cell