打开工作簿后在Excel中运行宏

时间:2018-02-16 14:12:12

标签: excel vba

我希望在工作簿打开后立即运行宏,原因是宏需要先打开工作簿。 <{1}}不是一个选项,因为宏打开其他文件,因此会导致无限循环。

如果我从VBA-Editor运行它,宏工作正常,但它总是抛出

  

运行时错误1004:对象Workbook_activate的方法Cells具有   失败

当我实际打开工作簿时。

这是我使用的代码:

_Global

Private Sub Workbook_Open() Call updateColumn("sheet", "Tabelle2", 1, 2) Call updateColumn("sheet", "Tabelle2", 5, 1) Call updateSG("Tabelle2", "sheet") End Sub 通过打开另一个excel文件并从那里同步数据来更新给定列。它工作正常,所以我不会在这里进入它。

问题始终在updateColumn子目录中。它与updateSG基本相同,但它也会迭代另一个文件,并将所需的条目排序到相应的列中。

updateColumn

End Sub

问题在于行

Private Sub updateSG(sheetname As String, adbSheet As String)
Dim adb As Workbook
Dim report As Workbook
Dim row As Range
Dim fak As String
Dim N As Long
Dim rownumber As Long
Set report = Workbooks("thisfile.xlsm")
Set adb = Workbooks.Open(report.Path & "/ADB.xls")
rownumber = Cells(adb.Sheets(adbSheet).Rows.Count, 1).End(xlUp).row
For i = 2 To rownumber
    fak = adb.Sheets(adbSheet).Cells(i, 1).Value
    Select Case fak
        Case "E"
            N = report.Sheets(sheetname).Cells(Rows.Count, "C").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "C").Value = adb.Sheets(adbSheet).Cells(i, 3)
        Case "G"
            N = report.Sheets(sheetname).Cells(Rows.Count, "D").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "D").Value = adb.Sheets(adbSheet).Cells(i, 3)
        Case "I"
            N = report.Sheets(sheetname).Cells(Rows.Count, "E").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "E").Value = adb.Sheets(adbSheet).Cells(i, 3)
        Case "M"
            N = report.Sheets(sheetname).Cells(Rows.Count, "F").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "F").Value = adb.Sheets(adbSheet).Cells(i, 3)
        Case "P"
           N = report.Sheets(sheetname).Cells(Rows.Count, "G").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "G").Value = adb.Sheets(adbSheet).Cells(i, 3)
        Case "T"
            N = report.Sheets(sheetname).Cells(Rows.Count, "H").End(xlUp).row + 1
            report.Sheets(sheetname).Cells(N, "H").Value = adb.Sheets(adbSheet).Cells(i, 3)
    End Select
Next
For i = 3 To 8
    report.Sheets(sheetname).Columns(i).RemoveDuplicates Columns:=Array(1)
Next
Workbooks("ADB.xls").Close SaveChanges:=False

并且选择案例中的行为

rownumber = Cells(adb.Sheets(adbSheet).Rows.Count, 1).End(xlUp).row

这些行基本上计算列中的元素。同样,如果我在Workbook打开时运行它,它会完美地运行,但在我实际打开文件时总是会抛出错误。

我希望有人可以帮助我。

亲切的问候

迈克尔

1 个答案:

答案 0 :(得分:1)

Cells不符合特定工作簿或工作表的条件。因此,它会回退到全局Cells,默认使用Cells对象,无论工作表是否为活动。未能正确确定对象范围是1004错误的首要原因。见this

改变这个:

Set adb = Workbooks.Open(report.Path & "/ADB.xls")
rownumber = Cells(adb.Sheets(adbSheet).Rows.Count, 1).End(xlUp).row

因为在上面的Cells语句中,Cells引用ActiveSheet(默认情况下),adbSheet名称可能是也可能不是Cells。如果该表未激活,则预计会出错。

为此,为了确保您对adb工作簿对象和adbSheet工作表有资格Set adb = Workbooks.Open(report.Path & "/ADB.xls") With adb.Sheets(adbSheet) rowNumber = .Cells(.Rows.Count,1).End(xlUp).Row End With

name