首页 > 解决方案 > vba 代码适用于一张工作表,但不适用于第二张工作表

问题描述

我正在尝试创建一个查找功能来查找输入的申请编号,然后将信息从正在搜索的单元格中放入单元格中。我只更改了原始公式的工作表名称和范围。没有什么不同。我收到一个错误

'1004' "无法获取 Range 类的 Activate 属性"

在 .activate

我能够通过在之前插入激活来使代码正常工作

    dim ReqNumber

那行得通,但是现在它告诉我搜索方法所需的对象。

    set cF= .Find

这给我带来了问题。我不太确定现在出了什么问题。

 Dim ReqNumber As Variant
ReqNumber = InputBox("Please Enter Requisition Number", "Information")

Dim FirstAddress As String, cF As Range

With ThisWorkbook.Sheets(" MthruF Schedule").Range("A:A")
    .Cells(1, 1).Activate
    'First, define properly the Find method
    Set cF = .Find(What:=ReqNumber, _
                after:=ActiveCell, _
                LookIn:=xlFormulas, _
                LookAt:=xlPart, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    'If there is a result, keep looking with FindNext method
    If Not cF Is Nothing Then
        FirstAddress = cF.Address
        Do
            cF.Offset(0, 8).Value = ReqNumber
            cF.Offset(0, 9).Value = EmpInfo.FirstName.Value & " " & EmpInfo.LastName.Value
            cF.Offset(0, 10).Value = EmpInfo.ComboBox3.Value & "/" & EmpInfo.ComboBox20.Value & "/" & EmpInfo.YearCmb.Value
            cF.Offset(0, 11).Value = EmpInfo.AgencyBox.Value
            Set cF = .FindNext(cF)
        'Look until you find again the first result
        Loop While Not cF Is Nothing And cF.Address <> FirstAddress
    End If
End With

标签: vbaexcel

解决方案


认为这是因为您在运行代码时选择了错误的工作表。
如果您不在正确的工作表上,则此代码将失败:

Worksheets("MthruF Schedule").range("A1").activate

无论您在哪个工作表上都执行搜索,请删除该.Cells(1,1).Activate行 - 您无需选择或激活单元格即可使用它。

FIND替换ActiveCell.Cells(1,1).

通过这些更改,无论您在哪个工作表上, 您都将始终查看从单元格开始的FINDA 列。MthruF ScheduleA1

编辑:
由于您没有更改您发现的值,因此无需Not cF Is Nothing在循环中使用。FIND除非您更改它,否则它将始终找到一个值 - 所以只需检查cF.Address <> FirstAddress.


推荐阅读