从Access VBA格式化Excel

时间:2017-01-02 11:10:53

标签: excel vba access-vba ms-access-2013 excel-2013

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

  

Object不支持此属性或方法

当语法到达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

1 个答案:

答案 0 :(得分:3)

这种语法可以def使用一些清理,但它应该让你接近你想要的输出。发表任何有关此问题的评论,我会尽力为您解决问题。

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