从Access VBA格式化Excel

我需要在工作簿中的单元格1之上添加一个新行。 我input了我认为正确的下面的语法,但是我得到一个错误:

对象不支持此属性或方法

当语法命中块的第二行 – .Rows("1:1").Select

为了使这个语法像预期的那样执行,我需要改变什么?

 Function AdddFormatting() Dim ExportRecordSet As DAO.Recordset Dim excelWS As Object, excelWS2 As Object Dim xl As Object Dim wb As Object Dim TemplateWB As String Set xl = CreateObject("Excel.Application") TemplateWB = "C:\Test\Testwb.xlsx" Set wb = xl.Workbooks.Add Set excelWS = wb.Worksheets(1) excelWS.Name = "AddedFromCode" Set excelWS2 = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)) excelWS2.Name = "AddedFromCode2" xl.Application.Visible = True With wb .Sheets(1).Activate .Rows("1:1").Select 'Using this syntax throws the same error '.Rows(1).Select .Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove .Range("A1:H1").Select .Selection.Merge .ActiveCell.FormulaR1C1 = "This is the text that will display as the header" .Range("A1:H1").Select.Font.Name = "Arial" .Range("A1:H1").Select.Font.Size = 15 .Range("A1").Activate End With End Function 

编辑
根据@ user2676140发表的评论,我改变了我with块的从with wbwith excelWS现在抛出第3行相同的错误 – 这一个:

 .Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 

这个语法可以使用一些清理,但它应该让你接近你想要的输出。 发表任何问题,这仍然给你一个评论,我会尽力引导你通过修复。

 excelWS.Activate excelWS.Rows(1).Select xl.Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove excelWS.Range("A1:H1").Activate xl.Selection.Merge xl.ActiveCell.FormulaR1C1 = "This is the text that will display as the header" excelWS.Range("A1:H1").Activate xl.Selection.Font.Name = "Arial" xl.Selection.Font.Size = 15 excelWS.Range("A1").Activate 

– > @ StarsFlyFree FromCozyNights < – 只能合并A1:H1试着改变这一行:

 excelWS.Range("A1:H1").Activate 

这个—->

 excelWS.Range("A1:H1").Select