我有两个电子表格;我将它们称为电子表格1和电子表格2.电子表格一有一个函数可以生成一个月中的几天,如果它在月末,则它试图调用电子表格2中的模块/子。这是为了生成“每日”报告和“每月”报告。两个问题 - 保存实例化工作簿中的更改并激活其他工作簿
在这一点上,有两个错误:第一个是当我试图保存我创建的电子表格2的新实例。错误是它要求以无宏格式保存工作簿。我只是想保存它!不要对格式进行任何更改。我甚至不确定它是否试图保存对实例化书对象的更改。
第二个是在电子表格2中,即使我将它设置为活动工作表(我认为),活动工作表仍然是电子表格1上的工作表,它首先运行宏。
任何帮助表示赞赏。
Option Explicit
Public Function LastWeekOfMonth() As Boolean
'finds the current date
Dim CurrentDate As Date
CurrentDate = CDate(ActiveSheet.Cells(FIRST_DATA_ROW, 1))
'find filepath and filename of the monthly documentation file
Dim mFilePath As String
Dim mFileName As String
mFilePath = "F:\Project Sweep\Kim Checklist\Barry Polinsky\Brathwaite, Tamika\"
mFileName = Cells(3, 4) & ".m_d.xlsm"
'if it is the last week of the month, write a monthly report, and return true to continue with the face to face paperwork
If (31 - Day(CurrentDate)) <= 7 Then
'write a monthly report
Dim app As New Excel.Application
Dim book As Excel.Workbook
' app.Visible = False 'Visible is False by default, so this isn't necessary
Set book = app.Workbooks.Add(mFilePath & mFileName)
'run the subroutine CheckSpreadsheet in module WriteReport in target book
app.Run "'" & mFilePath & mFileName & "'!" & "WriteReport" & ".CheckSpreadsheet", book
' CheckSpreadsheet (book)
'error next line
book.Save
book.Close
app.Quit
Set app = Nothing
LastWeekOfMonth = True
'if it is not, simply continue with the face to face paperwork
Else
LastWeekOfMonth = False
End If
End Function
在目标表中,在模块WriteReport,子程序CheckSpreadsheet,下面的代码的位置。
Option Explicit
Public Sub CheckSpreadsheet(wbook As Excel.Workbook)
Set wosheet = wbook.Sheets("Monthly")
wosheet.Cells(5, 5) = "Hello world!"
End Sub
如果您正在运行的代码位于Excel VBA中,是否存在打开“Excel.Application”的第二个实例的具体原因? – Jordan
希望能够打开工作簿2,而不是变得可见。我被其他帖子建议在这里的stackoverflow,做到这一点的方式是打开一个新的应用程序,因为工作簿对象没有.visible属性 – bdpolinsky
好吧。这个问题可能在于你正在使用'Application.Run'来调用你的'CheckSpreadsheet'子程序,它将从你的第一个Excel实例开始,然后你传递一个在你的第二个时间打开的'Excel.Workbook'变量Excel实例。尝试用'app.Run'替换'Application.Run',以便它从Excel的第二个实例运行该子例程 – Jordan