使用ExceL VBA访问以将数据格式化为Excel表

时间:2017-06-19 15:53:20

标签: excel vba ms-access

question。它显示了将Excel数据格式化为Excel格式的解决方案。

代码是

  Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

我正在尝试在Access VBA中使用此代码,我在其中使用Access数据创建Excel输出文件,然后我想以类似方式对其进行格式化。这是我的代码。

Dim objXL As Object
Dim objWorkbook As Object
Dim objWorkSheet As Object
Dim sourcefilepath As String
Dim tbl As ListObject
Dim rng As Range

Set objXL = New Excel.Application
objXL.Application.Visible = False

sourcefilepath = Application.CurrentProject.Path & "\CF Break Report " & Format(Date, "mm-dd-yy") & ".xls"
Set objWorkbook = objXL.Application.Workbooks.Open(FileName:=sourcefilepath)
Set objWorkSheet = objWorkbook.Worksheets("_400_CF_BREAK_LOG")

Set rng = objWorkSheet.Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell))
Set tbl = objWorkSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"

更新:失败的行是

   Set rng = objWorkSheet.Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell))

错误"应用程序定义或对象定义错误

2 个答案:

答案 0 :(得分:0)

尝试:

Set rng = objWorkSheet.Range(objWorkSheet.Range("A1"), ActiveCell.SpecialCells(xlLastCell))

为我工作。

答案 1 :(得分:0)

找到隐藏的答案here

With xlWB.Sheets("Summary")
Set rng = .Cells(1, 1).CurrentRegion
End With
Set tbl = xlWS.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
tbl.ShowTotals = True