多个运行时错误的问题:更新的代码 – 仍然有问题

谢谢大家的帮助到目前为止 – 非常感谢! 但是我仍然有问题

我是一个非常新的Excel用户,我相信答案会非常简单。

我经历了很多尝试,通过阅读现有的问题来解决这个问题,但是每次我只是得到一个不同的错误,并且无法解决问题。

正因为如此,我已经经历了许多代码尝试修复这些问题的迭代,因此欢迎关于如何继续的build议。

也道歉,如果我不格式/问我的问题适当。

背景

我有两个excel文件:wb1)一张带有公司名称和ID表的表(每周更改列表)wb2)带有多个选项卡的工作簿,其本质上就是模板。

对于在wb1中列出的每个公司,我需要将公司名称和ID复制到wb2中的相应单元格中,并另存为公司名称和date。

如上所述,我已经经历了许多迭代,并在下面得到了帮助,但是我仍然没有得到它的工作。

我得到的各种错误取决于我如何修改代码是运行时错误5,运行时错误438,编译错误,可能还有一些我没有写下来。

当前的问题:

如果macros保存在wb1中 – macros运行并创build第一个工作簿,但是然后我得到“系统错误&h800401a8(-2147221080)

如果macros保存在个人macros工作簿 – “脚本超出范围”。 它似乎打破了行Set tb1 = wb1.Sheets("Sheet1").ListObjects("Table1")

我会欢迎任何关于如何解决问题的build议,并提前致谢。

这是我的代码,因为它代表:

  Option Explicit Sub CreateStat() Dim CompanyName As String Dim CompanyID As String Dim Z As Long Dim wb1 As Workbook Dim wb2 As Workbook Dim tb1 As ListObject Dim i As Long Set wb1 = **struggling with this. I want to reference the workbook that has the table in it that is being used to draw through to the CompanyName and CompanyID. This is already open. The table is formatted as a table starting A1 with headers in row A**. (errors come when this is set to ThisWorkbook) Set wb2 = Workbooks.Open("C:\Users\YYY\Documents\Statements\SRTemplate.xlsx") Set tb1 = wb1.Sheets("Sheet1").ListObjects("Table1") Application.ScreenUpdating = False Application.DisplayAlerts = False wb1.Activate Sheets("Sheet1").Select Z = tb1.DataBodyRange.Rows.Count For i = 2 To Z + 1 CompanyID = tb1.DataBodyRange.Cells(i, 1) CompanyName = tb1.DataBodyRange.Cells(i, 2) wb2.Activate wb2.Sheets("Reconciliation").Range("D3").Value = CompanyName wb2.Sheets("Reconciliation").Range("M3").Value = CompanyID ChDir "C:\Users\hannah.wyld\Documents\Statements\" ActiveWorkbook.SaveAs Filename:= _ "C:\Users\YYY\Documents\Statements\" & CompanyName & " " & Format(Date, "MMM") & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False Windows(CompanyName & " " & Format(Date, "MMM") & ".xlsx").Close wb2.Activate wb2.Close wb1.Activate Next i End Sub