EXCEL VBA,搜索行错误1004

时间:2018-07-17 09:17:33

标签: excel vba excel-vba excel-formula excel-2010

我正在尝试运行excel vba表单来搜索行,但是由于某些未知原因,我得到了错误:

  

对象全局范围的方法范围失败

Private Sub CommandButton3_Click()
    Dim last, i As Integer
    Dim ref, lote As String
    'Sheets("analisegeral").Visible = True
    Sheets("analisegeral").Select
    last = Range("analisegeral").End(xlUp).Row + 1  

       For i = 2 To last                         ref = Cells(i, 8)
          lote = Cells(i, 13)

          If TextBox1.Text = ref Then
             TextBox2.Text = lote
             GoTo fim
          End If

       Next i

       If TextBox1.Text <> ref Then
          TextBox2.Text = ""
          MsgBox "Referência não encontrada!", vbInformation
          TextBox1.Text = ""
          TextBox2.Text = ""
          GoTo fim
       End If
    fim:
End Sub

1 个答案:

答案 0 :(得分:2)

您的代码很少出现问题。

无效的声明

Dim last, i As Integer
Dim ref, lote As String

请注意,lastref在此处声明为Variant类型,除非您有此意图,请将其更改为以下内容:

Dim last As Integer, i As Integer
Dim ref As String, lote As String

无法激活范围所在的工作表

'Sheets("analisegeral").Visible = True
Sheets("analisegeral").Select

工作表处于隐藏状态(或非常隐藏)的事实不允许对其进行选择。
可能是您的错误。

计算最后一行的方法错误

last = Range("analisegeral").End(xlUp).Row + 1

鉴于您实际上将选择 analisegeral 工作表,但这仍然没有意义:
Range("NamedRange")是一种结构,允许引用以前命名的范围(使用VBA或手动)。除非您有一个,否则将引发另一个错误。也许你的意思是这样的?

last = Range("A" & Rows.Count).End(xlUp).Row

这将为您提供许多 A列的最后一行。

最终建议:avoid using Select