运行 时间错误 1004 - vba 带变量的公式

Run time error 1004 - vba formula with variables

我正在尝试将一些代码粘贴到列 "B" 中的匹配函数中,该函数引用相邻列 "A" 中的同一行,使用列 [=26] 中的列表=] 在另一个 sheet 中作为查找数组。这一切发生的工作sheet是ws0,查找数组所在的sheet是ws2。

代码在 "With" 括号中的最后一行(跳到我的代码的底部)跳闸:

Cells(i, 2).Value = "=MATCH(A" & i & "," & ws2.Name & "!$A:$A$" & lRow1 & ", 0)""",

给我一个

Run-time error 1004. Application-defined or object-defined error.

我不知道是什么原因造成的。我觉得我的引号可能不正确,或者我的变量 lRow1、fRow、ws2 中的一个可能有问题,但我已经尽可能多地修改它们,但无济于事。任何想法将不胜感激!请注意,在抛出错误的那一行上方注释掉的行演示了公式的结果应该是什么样子。

Dim wb0 As Workbook 'this workbook (the log) '''''''''''''''''''''''
Dim wb1 As Workbook 'the opened T12 sheet
Dim rng0 As Range 'the range of cells in this workbook's 2nd sheet to be copied to
Dim rng1 As Range 'the range of cells from the opened workbook to be copied from
Dim rng2 As Range 'the range of the cells copied into ws0 from ws1
Dim fRow As Integer 'the first row of the range used in wb0, ws0
Dim lRow0 As Integer 'the last row of the range used in wb0, ws0
Dim lRow1 As Integer 'the last row of the range of accounts in ws2
Dim usedRng As Range 'the full range of cells used in wb0, ws0

Set ws0 = ActiveSheet
Set wb0 = ActiveWorkbook '''''''''''''''
Set rng0 = ws0.Range("A9:A159")

'Find the desired T12 workbook filepath
  'only allow the user to select one file
  Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
  'make the file dialog visible to the user
  fileChoice = Application.FileDialog(msoFileDialogOpen).Show
  'determine what choice the user made
  If fileChoice <> 0 Then
      'get the file path selected by the user
      filePath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
  End If

'Set variables using the newly-opened workbook
Set wb1 = Workbooks.Open(filePath)
Set ws1 = ActiveSheet
Set rng1 = ws1.Range("B9:B159")

'copy wb1, ws1's into wb0, ws0
rng0.Value = rng1.Value
wb1.Close

'create variable to refer to the first tab of wb0
wb0.Worksheets("Sheet1").Activate
Set ws2 = ActiveSheet

With ws2
    lRow1 = Cells(.Rows.Count, "A").End(xlUp).Row 'Last row
End With

'switch back to ws0
ws0.Activate

'identify the range used in ws0 of wb0
Set rng2 = ActiveSheet.UsedRange

fRow = rng2(1).Row 'First row

With ws0
    lRow0 = Cells(.Rows.Count, "A").End(xlUp).Row 'Last row
End With

Dim i As Integer
For i = fRow To lRow0
    With ws0
        'Cells(i, 2).Value = "=MATCH(A9,Sheet2!A9:A100,0)"
        Cells(i, 2).Value = "=MATCH(A" & i & "," & ws2.Name & "!$A:$A$" & lRow1 & ", 0)"""
    End With
Next i

End Sub

我在 Cells.Formula... 中遇到相同的错误,在 Range.Formula... 中遇到不同的 运行 时间错误 1004:"Method 'Range' of object _ Global failed." 任何建议将不胜感激!我包含了我的宏的全部内容供您参考……尽管相关部分在底部。提前致谢!

我认为这是你的 )""" 你只需要 1 个关闭 "