我有兩個電子表格;我將它們稱爲電子表格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