当我在 VBA 中使用 range.offset 时,我得到错误代码 1004 application defined object or object defined error due to synatx error

When I use range.offset in VBA, I get error code 1004 application defined object or object defined error due to synatx error

我正在尝试使用偏移函数,但无法找出我的 synatx 的问题。

我从这个网站上另一个关于偏移量的问题中复制了这段代码。

我想在 X 列(始终从 X9 开始)中查找字符串,如果存在,我想知道位于同一行上方两列的单元格的值。

我想在同一代码的附加部分使用偏移值,因此需要将其命名为变量,但我决定看看是否可以先将 VBA 至少阅读我想要的信息,因此消息框。

代码如下:

Private Sub CommandButton3_Click()
Dim LeftStrike As Range
Dim FrameLeftStrike As Range
Dim lastRow As Long

lastRow = Range("X" & Rows.Count).End(xlUp).Row
Set LeftStrike = Range("X9:X" & lastRow)
Set FrameLeftStrike = Range("LeftStrike").Offset(0, 4).Value
For Each FrameLeftStrike In LeftStrike
    If InStr(1, LeftStrike.Value, "Foot Strike") > 0 Then
        MsgBox FrameLeftStrike
    End If
Next FrameLeftStrike
End Sub

问题出在变量“FrameLeftStrike”上。

我收到:

application defined or object defined error.

我尝试了不同的迭代。

如果我将代码行更改为,

Set FrameLeftStrike = Sheet4.Range("LeftStrike").Offset(0, 4).Value

我得到同样的错误。

如果我把它改成

Set FrameLeftStrike = LeftStrike.Offset(0, 4).Value

我明白了

run-time error '424' Object required.

我只想在活动 sheet 中使用此代码,但活动 sheet 的名称会更改,因为它将被复制为其他项目的模板。

  1. 遍历 X 列 (my_range) 中的每个单元格 (my_cell)
  2. 单独检查单元格是否包含Foot Strike
  3. 如果是,return 值在 MsgBox
  4. 中右移 2 个单元格

Sub test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update

Dim my_range As Range, my_cell As Range
Dim lr As Long

lr = ws.Range("X" & ws.Rows.Count).End(xlUp).Row
Set my_range = ws.Range("X9:X" & lr)

For Each my_cell In my_range
    If InStr(my_cell, "Foot Strike") Then
        MsgBox my_cell.Offset(0, 2)
    End If
Next my_cell


End Sub