首页 > 解决方案 > 试图让一个单元格等于一个变量位置

问题描述

好的菜鸟在这里的vba。我正在尝试将工作表 2 上的单元格公式更新为等于工作表 1 上的另一个单元格。单元格工作表的位置可以并且将会改变。唯一的常数是与我需要的单元格相关的带有“InsertC”的单元格。

Range("O252").Select
ActiveCell.Formula = "=Sheet1!" & Cells.Find(What:="InsertC", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Offset(-2, 8).Address

当前错误是

运行时错误“91”对象变量或未设置块变量

标签: excelvba

解决方案


您将太多东西塞进一个可执行语句中。分裂。事物。向上。

Dim ws As Worksheet
Set ws = ActiveSheet 'TODO: get the actual sheet you want to work with.

Dim searchResult As Range
Set searchResult = ws.Cells.Find(What:="InsertC", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
'TODO: reconsider whether ActiveCell needs to be involved in the search.

If searchResult Is Nothing Then Exit Sub 'couldn't find what we're looking for; bail out!

Dim offsetCell As Range
On Error Resume Next 'next instruction may raise an error - ignore it
Set offsetCell = searchResult.Offset(-2, 8)
If offsetCell Is Nothing Then Exit Sub 'couldn't legally offset negative rows; bail out!
On Error GoTo 0 'resume raising runtime errors

ws.Range("O252").Formula = "=" & offsetCell.Address(External:=True)

请注意,工作表的名称不需要在公式中硬编码 -offsetCell.Address 如果您指定参数,可以为您True计算External出来。

这将使公式为 eg =[Book1]Sheet1!$A$1,但在[Book1]成功分配公式后,该部分将被 Excel 优化掉。


推荐阅读