在PowerPoint中获取周数

时间:2015-10-20 23:33:31

标签: excel vba function excel-vba powerpoint

我有一个用Excel文件生成PowerPoint的代码。我根据我的要求大部分修改了代码,但我想在我的.ppt中再添加一个功能。我希望VBA从某些来源提取周数并执行以下操作:

  1. 将我的.ppt重命名为" XXX_Weeknumber.ppt"
  2. 在幻灯片中的一个文本框中,我想添加相同的Weeknumber。
  3. 我尝试使用函数WeekNum获取周数,并尝试在我的主Sub中调用该函数,但遗憾的是无法工作!

    我在模块1中的功能代码:

    Function WeekNum(D As Date) As Integer
    WeekNum = CInt(Format(D, "ww", 2))
    End Function
    

    模块2中.xls到.ppt的代码:

    Dim oPPTApp As PowerPoint.Application
    Dim oPPTShape As PowerPoint.Shape
    Dim oPPTShape2 As PowerPoint.Shape
    Dim oPPTFile As PowerPoint.Presentation
    Dim PPSlide As PowerPoint.slide
    Dim SlideNum As Integer
    Dim rng As Range
    Dim WeekNumm$
    
    
    Sub PPTableMacro()
    Dim sourcexl As Workbook
    
    Dim wk As Integer
    
    Dim strPresPath As String, strExcelFilePath As String, strNewPresPath As String
    strExcelFilePath = "C:\MySource.xls"
    strPresPath = "C:\Presentation1.ppt"
    Call WeekNum
    WeekNumm = WeekNum()
    Set wk = WeekNumm
    strNewPresPath = "C:\Presentation1_" & wk & ".ppt" 'This is how I want the name
    strNewPresPath = "C:\new1.ppt"
    
    Set oPPTApp = CreateObject("PowerPoint.Application")
    oPPTApp.Visible = msoTrue
    
    Set oPPTFile = oPPTApp.Presentations.Open(strPresPath)
    SlideNum = 2
    
    oPPTFile.Slides(SlideNum).Select
    Set oPPTShape = oPPTFile.Slides(SlideNum).Shapes("Table 1")
    
    Set sourcexl = Workbooks.Open(strExcelFilePath) 'Source excel file
    With sourcexl
    .Sheets("Sheet1").Activate
    oPPTShape.Table.Cell(1, 1).Shape.TextFrame.TextRange.Text = Cells(1, 1).Text
    oPPTShape.Table.Cell(1, 2).Shape.TextFrame.TextRange.Text = Cells(1, 2).Text
    oPPTShape.Table.Cell(1, 3).Shape.TextFrame.TextRange.Text = Cells(1, 3).Text
    oPPTShape.Table.Cell(2, 1).Shape.TextFrame.TextRange.Text = Cells(2, 1).Text
    oPPTShape.Table.Cell(2, 2).Shape.TextFrame.TextRange.Text = Cells(2, 2).Text
    oPPTShape.Table.Cell(2, 3).Shape.TextFrame.TextRange.Text = Cells(2, 3).Text
    
    End With
    
    Set oPPTShape2 = oPPTFile.Slides(SlideNum).Shapes("TextBox 1")
    Text1 = "weekXX" ' actually wanted week number here
    oPPTShape2.TextFrame.TextRange.Text = Text1
    
    oPPTFile.SaveAs strNewPresPath
    'oPPTFile.Close
    'oPPTApp.Quit
    
    Set oPPTShape = Nothing
    Set oPPTFile = Nothing
    Set oPPTApp = Nothing
    
    MsgBox "Presentation Created", vbOKOnly + vbInformation
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

您的功能要求输入数据(" D"),并且它不是可选的。如果你想检索今天的星期几("日期"系统变量),你应该这样称呼它:

WeekNumm = WeekNum(Date)

此外,您在" Set wk = WeekNumm"中使用Set语句。由于变量不是一个对象,你必须使用(最好省略)Let。

此外,您的功能不会返回星期几,因为" ww"表示一年中的周数。如果你想通过这种方法得到星期几,你必须使用" w"。

为了更好的方法,你应该使用内置函数Weekday来获得工作日。

像:

iWeekDay = Weekday(Date,vbUseSystemDayOfWeek) 'Retrieves today's day of the week (Tuesday = 3...)