EXCEL VBA , 搜索行错误 1004

EXCEL VBA , Search Line Error 1004

我正在尝试 运行 一个 excel vba 表格来搜索所有行,但由于某些未知原因我得到错误:

Method Range of object Global failed

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

您的代码几乎没有问题。

声明无效

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

无法激活工作sheet范围所在

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

你的 sheet 是隐藏的(或非常隐藏的)这一事实不允许它是 selection。
可能这就是你的错误。

最后一行的计算方法错误

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

鉴于你实际上 select 分析 sheet,这仍然没有意义:
Range("NamedRange") 是一种允许引用先前命名范围的结构(使用 VBA 或手动)。除非你有一个,否则这将引发另一个错误。也许你的意思是这样的?

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

这将为您提供 A 列 最后一行的数字。

最终建议:avoid using Select