简体   繁体   English

从 Access VBA 格式化 Excel

[英]Format Excel From Access VBA

I am in need to add a new row above Cell 1 in my workbook.我需要在我的工作簿中的单元格 1 上方添加一个新行。 I typed out the below syntax which I believe is correct, but I am getting an error of:我输入了以下我认为正确的语法,但出现以下错误:

Object does not support this property or method对象不支持此属性或方法

When the syntax hits the second line of my with block - .Rows("1:1").Select当语法到达 my with块的第二行时 - .Rows("1:1").Select

What do I need to alter in order for this syntax to execute as expeceted?我需要更改什么才能使此语法按预期执行?

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

EDIT编辑
Per the comment posted by @user2676140 I altered my with block from with wb to with excelWS which now throws the same error on line 3 - this one:根据@user2676140 发布的评论,我将with块从with wb更改为with excelWS ,现在在第 3 行抛出相同的错误 - 这个错误:

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

This syntax can def use some cleaning up but it should get you close to your desired output.这个语法可以定义一些清理,但它应该让你接近你想要的输出。 Post a comment with any issues that this still brings you and I will try to walk you through a fix.对这仍然给您带来的任何问题发表评论,我将尝试引导您完成修复。

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<- to only merge A1:H1 try changing this line: ->@StarsFlyFree FromCozyNights<- 仅合并 A1:H1 尝试更改此行:

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

to this ---->对此---->

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM