我刚接触VBA(不到一个星期大)。我正在尝试创建一个宏,该宏将基于幻灯片1上表格中提供的文件路径和幻灯片范围在当前演示文稿中插入幻灯片。我创建了以下代码,但我认为我做错了事,因为它不起作用。请帮忙...
Sub Insert_Slides()
Dim sl As Slide
Dim tbl As Table
Dim shp As Shape
Dim filepath As String
Dim slidestart As String
Dim slideend As String
Set sl = ActivePresentation.Slides(1)
Set tbl = sl.Shapes("Contents").Table
Set filepath = ActivePresentation.Slides(1).Shapes("Contents").Table.Cell(2, 1).Select
Set slidestart = ActivePresentation.Slides(1).Shapes("Contents").Table.Cell(2, 2).Select
Set slideend = ActivePresentation.Slides(1).Shapes("Contents").Table.Cell(2, 3).Select
ActivePresentation.Slides.InsertFromFile _
filepath, 1, slidestart, slideend
End Sub
答案 0 :(得分:0)
Ashwin,
对于新的VBA用户而言不明显的两个提示:
1)始终使用Option Explicit启动每个模块。如果您转到工具|选项|编辑器选项卡,然后在“要求变量声明”旁边打勾,VBA将自动为您执行此操作。除非您使用Mac。
1a)如果您在变量名中使用了不同类型的大小写... FilePath或Filepath而不是filepath ...,则可以使用任意方式键入名称,VBA编辑器会将大小写更改为您所需要的ve宣布。如果不是,则说明您输入了错误的变量名或没有首先声明它。
2)总是选择Debug |在尝试运行代码之前进行编译。继续进行编译,直到找到并修复所有编译器错误为止。
这是您代码的修改版本。我没有时间来设置一组测试演示文稿来进行尝试,但是我会给你带来很多方便的机会。试一试,让我们知道其效果。
Option Explicit
Sub Insert_Slides()
Dim sl As Slide
Dim tbl As Table
Dim shp As Shape
Dim filepath As String
' These need to be Longs, not Strings
Dim slidestart As Long
Dim slideend As Long
Set sl = ActivePresentation.Slides(1)
Set tbl = sl.Shapes("Contents").Table
' Use SET to assign objects to object variables, but not to assign values to
' string/numeric variables such as you're using.
' AND never select anything unless there's an absolute need to. It can slow your code down by a factor of 10 and
' can prevent it from running in some circumstances.
' AND by using With/End With you can shorten the code considerably;
' easier to read and, at least in theory, runs a bit faster
' SO ...
'Set filepath = ActivePresentation.Slides(1).Shapes("Contents").Table.Cell(2, 1).Select
With ActivePresentation.Slides(1).Shapes("Contents").Table
filepath = .Cell(2, 1).Shape.TextFrame.TextRange.Text
' since the table cells contain text (strings), you should convert them to Longs before assigning
' them to a Long variable:
slidestart = CLng(.Cell(2, 2).Shape.TextFrame.TextRange.Text)
slideend = CLng(.Cell(2, 3).Shape.TextFrame.TextRange.Text)
End With
' and you might want to add a test here;
' make sure the file exists before trying to access it:
If Len(Dir$(filepath)) > 0 Then
ActivePresentation.Slides.InsertFromFile _
filepath, 1, slidestart, slideend
Else
MsgBox "Cannot locate file " & filepath
End If
End Sub