2017-06-19 164 views
0

請參閱此question。它顯示了一個將Excel數據格式化爲Excel表格的解決方案。使用ExceL VBA以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 

我想,我創建訪問數據的Excel輸出文件,然後我想類似的格式,它可以利用VBA訪問該代碼。這是我的代碼。

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)) 

隨着錯誤「應用程序定義或對象定義的錯誤

+0

關閉「嘗試 –

+0

被關閉。複製到此網站不起作用。對不起,將更新 – FamousFrik

+0

在行之前插入一個斷點並查看tablestyle是什麼。它不會被跳過,如果它不存在,所以它可能會出錯,但你可能有錯誤陷阱跳過它 –

回答

0

嘗試:

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

曾爲對我來說

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