VBA常数问题

时间:2019-04-29 14:58:20

标签: excel vba powerpoint

今天早些时候,我出现了运行时错误448(找不到命名对象),它包含以下用Excel编写的代码:

Sub PPTextbox()

Dim PowerPointApp As PowerPoint.Application
Dim myPresentation As PowerPoint.Presentation
Dim mySlide As Object
Dim DestinationPPT As String

Set PowerPointApp = CreateObject("PowerPoint.Application")
DestinationPPT = "H:\VBA\Kapitalanlageplanung - Präsentationen\Monatsbericht\MonatsberichtTemplate.pptm"
Set myPresentation = PowerPointApp.Presentations.Open(DestinationPPT)
Set mySlide = myPresentation.Slides.Add(myPresentation.Slides.Count + 1, 12)

mySlide.Shapes.AddTextbox(Type:=msoTextOrientationHorizontal, Left:=100, Top:=100, Width:=200, Height:=50).TextFrame.TextRange.Text = "Test Box"

End Sub

事实证明,问题出在Type:=msoTextOrientationHorizontal上,用简单的1代替就可以了。

This comment I found给了我解决方案。我知道现在我通过将mySlide声明为Object来使用后期绑定。我知道现在它效率低下,显然会导致一些类似我遇到的问题。但为什么?后期绑定时,它背后是否有逻辑?或者我是否只需要接受“无法识别某些VBA常量并将它们视为变量”?另外,这是随机发生的,因为之前的代码完全相同吗?

1 个答案:

答案 0 :(得分:1)

我总是使用后期绑定,以便我的代码可以在其他PC上运行而无需激活依赖项。可移植性至关重要。然后,我想定义将由早期绑定手动设置的常量。

Const msoTextOrientationHorizontal = 1    

Sub PPTextbox() 
    Dim PowerPointApp As Object
    Set PowerPointApp = CreateObject("PowerPoint.Application")
    Dim DestinationPPT As String
    DestinationPPT = "H:\VBA\Kapitalanlageplanung - Präsentationen\Monatsbericht\MonatsberichtTemplate.pptm"
    Dim myPresentation As Object
    Set myPresentation = PowerPointApp.Presentations.Open(DestinationPPT)
    Dim mySlide As Object
    Set mySlide = myPresentation.Slides.Add(myPresentation.Slides.Count + 1, 12)

    mySlide.Shapes.AddTextbox(Type:=msoTextOrientationHorizontal, Left:=100, Top:=100, Width:=200, Height:=50).TextFrame.TextRange.Text = "Test Box" 
End Sub