格式 Excel 来自 Access VBA

Format Excel From Access VBA

我需要在我的工作簿中的单元格 1 上方添加一个新行。我输入了我认为正确的以下语法,但我收到以下错误:

Object does not support this property or method

当语法到达我的 with 块的第二行时 - .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 wb 更改为 with excelWS 现在在第 3 行抛出相同的错误 - 这个:

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

此语法可以明确地使用一些清理,但它应该让您接近您想要的输出。 Post 对这仍然给您带来的任何问题发表评论,我将尝试引导您完成修复。

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