我是Macros的新手。我想做数据透视表。我不能在excel中使用VBA宏,而是可以在外部使用VBscript编写并以“ .VBS”文件执行。尽管我设法创建了excel对象并放置了数据,但是在创建数据透视表时遇到了困难。我知道VBA和vbscript相似,因此我尝试使用VBA,如下所示:
首先,我尝试使用Vbscript创建excel对象:
Set obj = createobject("Excel.Application")
obj.visible = True
Set obj1 = obj.Workbooks.Add
obj.Cells(1,1).Value = "NM"
obj.Cells(1,2).Value = "VL"
obj.Cells(2,1).Value = "A"
obj.Cells(2,2).Value = 1
obj.Cells(3,1).Value = "B"
obj.Cells(3,2).Value = 2
obj.Cells(4,1).Value = "C"
obj.Cells(4,2).Value = 3
obj.Cells(5,1).Value = "D"
obj.Cells(5,2).Value = 4
然后我尝试使用VBA宏(内置excel宏)在excel文件本身中透视表。
Sub Macro1()
'
' Macro1 Macro
'
'
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R5C2", Version:=6).CreatePivotTable TableDestination:= _
"Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("VL")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NM")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("NM").CurrentPage = "(All)"
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NM")
.PivotItems("A").Visible = False
.PivotItems("C").Visible = False
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("NM"). _
EnableMultiplePageItems = True
Application.Goto Reference:="Macro1"
End Sub
现在我正在尝试使用VBScript进行相同的操作,但是我没有得到。 我尝试使用相同的并做了更改,例如添加excel对象名称 之前的方法,但仍然无法正常工作。
Set obj = createobject("Excel.Application")
obj.visible = True
Set obj1 = obj.Workbooks.Add
obj.Cells(1,1).Value = "NM"
obj.Cells(1,2).Value = "VL"
obj.Cells(2,1).Value = "A"
obj.Cells(2,2).Value = 1
obj.Cells(3,1).Value = "B"
obj.Cells(3,2).Value = 2
obj.Cells(4,1).Value = "C"
obj.Cells(4,2).Value = 3
obj.Cells(5,1).Value = "D"
obj.Cells(5,2).Value = 4
'Tried making changes:
'Adding Excel object
Obj.ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R5C2", Version:=6).CreatePivotTable TableDestination:= _
"Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion:=6
'Even Adding Excel workbook object
Obj1.ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R5C2", Version:=6).CreatePivotTable TableDestination:= _
"Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion:=6
它显示出缺少括号的错误,所以我什至试图将其放在一行中。
obj.ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="R1C1:R6C2", Version:=6).CreatePivotTable TableDestination:= _"Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion:=6
但仍显示与“ 错误:预期')'”(在同一行中的 )相同的错误。但是,这对于VBA宏来说是正确的语法,但是在执行vbscript的过程中会引发错误。有什么语法上的差异或需要做的更改。
任何人都可以帮助我或建议我如何做或完成它。