错误: - 同时运行2个函数时,对象'_global'的方法'范围'失败

问题描述 投票:0回答:1

我已经制作了两个函数“WrongEntries”和“Duplicates”。当我单独运行它时它运行得很好。但是当我一个接一个地运行它时,它反映了对象'_global'失败的方法'范围'。

我不确定是因为仍然在前一个运行函数的内存中的对象,但我确实在两个函数中使用了不同的对象和变量仍然存在相同的错误。还尝试把对象放在一边。

斯坦格的一部分是,如果我洗牌他们的第一个,总是完美运行并不重要它是什么。

Function WrongEntries()
Dim dbs As Database Dim lRow As Long Dim lCol As Long Dim rg As Range

Set dbs = CurrentDb
Set rgQuery = dbs.OpenRecordset("5G High Cycle Times")
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set targetWorkbook = excelApp.Workbooks.Open("\5G Wrong             
Entries_Blank.xlsx")
targetWorkbook.Worksheets("Cycle Times >5 
weeks").Range("A2").CopyFromRecordset rgQuery
targetWorkbook.Worksheets("Cycle Times >5 weeks").Activate

lRow = Range("b" & Rows.Count).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
excelApp.Quit
Set excelApp = Nothing
End Function

'''问题是当我第一次和第一次'''一起跑

Function Duplicates()

Dim dbs As Database Dim lastRw As Long Dim lastCl As Long Dim rnge As 
Range Dim wks As Worksheet
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set dbs = CurrentDb
Set rdQuery = dbs.OpenRecordset("5G Duplicates Check")
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set targetWorkbook = excelApp.Workbooks.Open("\5G Duplicates_Blank.xlsx")
Set wks = targetWorkbook.Worksheets("Duplicates")
targetWorkbook.Worksheets("Duplicates").Range("A2").CopyFromRecordset 
rdQuery

这里错误反映了计算最后一行计数

lastRw = wks.Range("a" & Rows.Count).End(xlUp).Row
lastCl = wks.Cells(1, Columns.Count).End(xlToLeft).Column
End Function
vba access-vba
1个回答
2
投票

您关闭应用程序:

excelApp.Quit
Set excelApp = Nothing

离开工作簿和所有孤立的对象。所以:

targetWorkbook.Close
Set targetWorkbook = Nothing
excelApp.Quit
Set excelApp = Nothing

进一步:始终使用特定对象。不

Range("b" & Rows.Count).End(xlUp).Row
Cells(1, Columns.Count).End(xlToLeft).Column

但:

Set range = SomeWorksheet.Range ...
set cell = SomeWorksheet.Cells ...

并作为第一个终止这些:

Set cell = Nothing
Set range = Nothing
Set wks = nothing
targetWorkbook.Close
Set targetWorkbook = Nothing
excelApp.Quit
Set excelApp = Nothing
© www.soinside.com 2019 - 2024. All rights reserved.