我每天都会创建一个文件,从不同的Excel工作表收集数据,每天只进行一次计算。创建此文件时,此文件每天使用的次数不同。此文件由宏创建(如果它尚不存在)。当我打开文件时,它会显示在屏幕上。为了隐藏打开所有这些文件,我创建了第二个保持隐藏的excel实例。问题是我无法在第二个实例中在工作表中创建表。
这是代码:
Dim app As New Excel.Application
app.Visible = False
Set newWB = app.Workbooks.Add
With newWB
.Title = "Summarizing of systemparts information"
.Subject = "Systemparts"
.SaveAs assembledSheet
End With
app.newWB.Sheets("SystemParts").ListObjects.Add(xlSrcRange, Range("$A$1:$CN$55"), , xlYes).Name = "SystemP"
app.ActiveSheet.ListObjects("SystemP").TableStyle = "TableStyleLight8"
有没有办法解决这个问题?
答案 0 :(得分:0)
您正在尝试将表格添加到尚未创建的工作表中。 您创建新工作簿,但无法指定哪个工作表是'SystemParts'。
Sub Test()
Dim app As Excel.Application
Dim newWB As Workbook
Dim newWS As Worksheet
Dim x As Long
'Create new Excel instance and add a new workbook.
Set app = New Excel.Application
Set newWB = app.Workbooks.Add
With newWB
'Add a sheet to the end of the workbook.
Set newWS = .Worksheets.Add(, .Worksheets(.Worksheets.Count))
'Remove all other sheets.
'As you delete sheet Index 1 - the next sheet replaces it,
'so just remove the first index each time.
Application.DisplayAlerts = False
For x = 1 To .Worksheets.Count - 1
.Worksheets(1).Delete
Next x
Application.DisplayAlerts = True
'Name the new sheet and add a table.
With newWS
.Name = "SystemParts"
.ListObjects.Add(xlSrcRange, .Range("$A$1:$CN$55"), , xlYes).Name = "SystemP"
.ListObjects("SystemP").TableStyle = "TableStyleLight8"
End With
.SaveAs ThisWorkbook.Path & "\NewWB.xlsx"
End With
End Sub