我正在尝试编写PowerPoint VB应用程序,该应用程序需要以固定格式显示文本文件中的某些值。
当我(手动)在Excel中将文本文件作为csv文件打开时,我在固定的单元格中获得了所需的值,并且我知道如何通过VBA从那里继续。
我不知道如何使用PowerPoint中的宏创建Excel电子表格。 另外,我想确保在宏中定义了用于打开文件的参数(使用空格作为定界符;多个空格视为一个),这样我就不必依赖当前的本地设置。
在此先感谢您提供任何想法或参考。
答案 0 :(得分:0)
2。使用扩展名不是.csv的文本文件 如果扩展名为“ .csv”,则Excel无法使用其他定界符加载文本
以下宏读取带有空格字符分隔符的文本文件,并将Excel表复制到幻灯片上的Powerpoint表。
完整代码:
Sub ReadCSV()
Dim xlsApp As Excel.Application
Dim xlsWb As Excel.Workbook
Dim xlsSht As Object 'Excel.Worksheet
Dim rng As Object 'Excel.Range
Dim Target As String
On Error GoTo Oops
'Set xlsApp = New Excel.Application
Set xlsApp = CreateObject("Excel.Application")
xlsApp.Visible = True
Target = ActivePresentation.Path & "\test_space.txt"
'Below don't support consecutive delimiters
'Set xlsWb = xlsApp.Workbooks.Open(FileName:=Target, Format:=3)
'File Extension .CSV won't work here. .TXT works.
xlsApp.Workbooks.OpenText FileName:=Target, Origin:=2, StartRow:=1, _
DataType:=1, ConsecutiveDelimiter:=True, Space:=True, Local:=True
Set xlsWb = xlsApp.ActiveWorkbook
Set xlsSht = xlsWb.Worksheets(1)
Dim sld As Slide
Dim shp As Shape
Dim tbl As Table
Dim numRow As Long, numCol As Long
Dim r As Long, c As Long
Set rng = xlsSht.UsedRange
numRow = rng.Rows.Count
numCol = rng.Columns.Count
With ActivePresentation
Set sld = .Slides.Add(.Slides.Count + 1, ppLayoutBlank)
End With
Set shp = sld.Shapes.AddTable(numRow, numCol, 100, 100, 200, 150)
shp.Name = "Table"
Set tbl = shp.Table
'Copy cell values from Excel Table to Powerpoint Table
For r = 1 To numRow
For c = 1 To numCol
tbl.Cell(r, c).Borders(ppBorderBottom).ForeColor.RGB = rgbBlack
With tbl.Cell(r, c).Shape.TextFrame
If r > 1 Then .Parent.Fill.ForeColor.RGB = rgbWhite
.VerticalAnchor = msoAnchorMiddle
.TextRange = rng.Cells(r, c)
.TextRange.ParagraphFormat.Alignment = ppAlignCenter
End With
Next c
Next r
xlsWb.Close False
Oops:
If Err.Number Then MsgBox Err.Description
'If Excel App remains in the system process, Excel App won't respond and run again.
If Not xlsApp Is Nothing Then xlsApp.Quit: Set xlsApp = Nothing
End Sub