Error referencing cells in a table after adding table - vba

I'm writing a routine that builds a TOC in a presentation based on the existence of 'Section Divider Slides' (Custom Layout Slide). When I try to build the TOC per se in a table that I add on a 'Table of Contents' custom slide, trying to set the .cell values I get an 'Object does not support this property or method'. I think it may have to do with the way I add the table and reference it but I can't figure it out.
The problematic code is just before the pseudo code for the rest of the routine starts. Bare in mind it's a first run so it may not be polished.
Thanks in advance.
Option Explicit
Sub BuildTOC()
Dim oSlide As slide
Dim i As Single
Dim myCol As Collection
Dim myColDividers As Collection
Dim UserInput As Variant
Dim InputQuestion As String
Dim SectionCount As Single
Dim DeleteTOCs As Long
Dim TOCSlide As Single
Dim SlideNum As Single
Dim TitleText As String
Dim oTable As Shape
Dim tRows As Long
Dim tCols As Long
Dim tLeft As Single
Dim tTop As Single
Dim tWidth As Single
Dim tHeight As Single
Dim tCol1Width As Single
Dim tCol2Width As Single
Dim tCol3Width As Single
Set myCol = New Collection
Set myColDividers = New Collection
If ActivePresentation.Slides.Count = 0 Then Exit Sub
'' Get number of dividers
SectionCount = 0
For i = 1 To ActivePresentation.Slides.Count
Debug.Print i & ": " & ActivePresentation.Slides(i).CustomLayout.Name
If ActivePresentation.Slides(i).CustomLayout.Name = "Section Divider" Then
SectionCount = SectionCount + 1
End If
Next i
Debug.Print "==================================="
'' loop through slides and add TOC layouts to collection
For i = 1 To ActivePresentation.Slides.Count
Debug.Print i & ": " & ActivePresentation.Slides(i).CustomLayout.Name
If ActivePresentation.Slides(i).CustomLayout.Name = "Table of Contents" Then
myCol.Add CStr(i), CStr(i)
End If
Next i
'' if no TOCs found, exit
If myCol.Count > 0 Then
'' Delete TOCs found
DeleteTOCs = MsgBox("This will delete all existing Tables of Contents." & vbNewLine & "Continue?", vbYesNo)
If vbYes Then
i = 0
For i = myCol.Count To 1 Step -1
ActivePresentation.Slides(val(myCol.item(i))).Delete
Debug.Print "Delete TOC on slide " & myCol.item(i)
Next
End If
End If
' Select position for TOC
' Keeping looping until we get a valid answer
InputQuestion = "Insert TOC before which slide number?" & vbNewLine & _
"Please input a number between 1 and " & ActivePresentation.Slides.Count & "."
Do
'Retrieve answer from the user
UserInput = InputBox(InputQuestion, "Table of Contents Position")
'Check if user selected cancel button
If StrPtr(UserInput) = 0 Then Exit Sub
'Check if user clicked OK without entering a value
If UserInput = vbNullString Then
MsgBox ("You must enter a value or click on Cancel")
End If
Loop While UserInput < 1 Or UserInput > ActivePresentation.Slides.Count
' Insert it
Set oSlide = ActivePresentation.Slides.AddSlide(UserInput, GetLayout("Table of Contents"))
TOCSlide = oSlide.SlideIndex
Debug.Print "==================================="
'' loop through slides and add TOC layouts to collection
For i = 1 To ActivePresentation.Slides.Count
Debug.Print i & ": " & ActivePresentation.Slides(i).CustomLayout.Name
If ActivePresentation.Slides(i).CustomLayout.Name = "Table of Contents" Then
myColDividers.Add CStr(i), CStr(i)
End If
Next i
Debug.Print "==================================="
'' Loop through slides and collect dividers
For i = 1 To ActivePresentation.Slides.Count
Debug.Print i & ": " & ActivePresentation.Slides(i).CustomLayout.Name
If ActivePresentation.Slides(i).CustomLayout.Name = "Section Divider" Then
myColDividers.Add CStr(i), CStr(i)
End If
Next i
' set Rows and Columns
tRows = SectionCount
tCols = 3
' Table dimensions
tLeft = CentimetersToPoints(9.09)
tTop = CentimetersToPoints(6.13)
tWidth = CentimetersToPoints(22.74)
tHeight = 24 ''CentimetersToPoints(11.72)
tCol1Width = CentimetersToPoints(2.7)
tCol2Width = CentimetersToPoints(17.4)
tCol3Width = CentimetersToPoints(2.7)
'' Create table
Set oSlide = Nothing
Set oSlide = ActivePresentation.Slides(TOCSlide)
Call DeleteTablesFromSlide(oSlide)
Set oTable = oSlide.Shapes.AddTable(tRows, tCols, tLeft, tTop, tWidth, tHeight)
With oTable.Table
.Columns(1).Width = tCol1Width
.Columns(2).Width = tCol2Width
.Columns(3).Width = tCol3Width
Debug.Print "======================================"
i = 0
For i = 1 To myColDividers.Count
SlideNum = val(myColDividers.item(i))
TitleText = ActivePresentation.Slides(SlideNum).Shapes.Title.textFrame.textRange.text
If ActivePresentation.Slides(SlideNum).Shapes.HasTitle Then
If Len(TitleText) > 0 Then
Debug.Print SlideNum & ": " & TitleText
.cell(i, 1) = i
.cell(i, 2) = TitleText
.cell(i, 3) = SlideNum
End If
Else
Debug.Print "No title"
.cell(i, 1) = i
.cell(i, 2) = " No title"
.cell(i, 3) = SlideNum
End If
Next i
End With
' For RowNum = 1 To SectionCount
' .cell(RowNum, 1) = RowNum
' .
' With shp.Table.cell(RowNum, 1).Shape.textFrame.textRange.ActionSettings(ppMouseClick).Hyperlink
' .SubAddress = .cell(RowNum, 1).Shape.textFrame.textRange.text
' .TextToDisplay = .cell(RowNum, 1).Shape.textFrame.textRange.text
' End With
'' 'slide number col
'' With shp.Table.cell(i - 1, 2).Shape.textFrame.textRange.ActionSettings(ppMouseClick).Hyperlink
'' .SubAddress = shp.Table.cell(i - 1, 2).Shape.textFrame.textRange.text
'' .TextToDisplay = shp.Table.cell(i - 1, 2).Shape.textFrame.textRange.text
'' End With
''Next i
'' Format TOC
''
''
''Next
''paste Table
''
''
''i = 0
''x = 0
''Set mycoll = Nothing
''
''For Each oSlide In ActivePresentation.Slides
''
'' If oSlide.layout = divider
'' Add to collection
''
''Find the table
''
''For Each oShape In oSlide.Shapes
''
''''
''End If
''
'' Oslide table delete
'' End If
''Next
''
''
''For i = 1 to slide count
'' If slide(i) layout = divider
'' Add to mycoll
''Next
''i = 0
''
''For i = 1 To mycoll.Count
''slide (i)
''Paste Table
''Format row i to highlight row position
''Next
End Sub
Public Function GetLayout( _
LayoutName As String, _
Optional ParentPresentation As Presentation = Nothing) As CustomLayout
Dim oLayout As CustomLayout
If ParentPresentation Is Nothing Then
Set ParentPresentation = ActivePresentation
End If
For Each oLayout In ParentPresentation.SlideMaster.CustomLayouts
If oLayout.Name = LayoutName Then
Set GetLayout = oLayout
Exit For
End If
Next
End Function
Public Function DeleteTablesFromSlide(mySlide As PowerPoint.slide) As Long
Dim lCntr As Long
Dim lTables As Long
' Count backwards when deleting items from a collection
For lCntr = mySlide.Shapes.Count To 1 Step -1
With mySlide.Shapes(lCntr)
Select Case .Type
Case msoTable: .Delete: lTables = lTables + 1 ' msoTable = 19
Case msoPlaceholder ' msoPlaceholder = 19
If .PlaceholderFormat.ContainedType = msoTable Then .Delete: lTables = lTables + 1
End Select
End With
Next
DeleteTablesFromSlide = lTables
End Function

As #timothyrylatt pointed out, my mistake was in how I was trying to manipulate the cells.
Instead of:
.cell(row,col) = Text
it should be:
.Cell(row, col).Shape.TextFrame.TextRange.Text = Text

Related

Powerpoint VBA actively select slide range based on string in textbox

I want to scan thorough a slide deck for text boxes containing a search string and leave the active presentation with Active selected slides.
*** I can search ok...>> Creating a list of slides with my text on
Function FindSlidesWithText(ByVal Owner As String) As String
Dim oSl As Slide
Dim oShp As Shape
Dim strSearch As String
Dim i As Integer
Dim slideList As String
If Owner = "" Then
strSearch = InputBox("Enter the text to search for:")
Else
strSearch = Owner
End If
Dim SomeoneSlides As String
SomeoneSlides = ""
SomeoneSlides = ""
For Each oSl In ActivePresentation.Slides
For Each oShp In oSl.Shapes
If oShp.HasTextFrame Then
If InStr(1, oShp.TextFrame.TextRange.Text, strSearch, vbTextCompare) > 0 Then
slideList = slideList & "Slide " & oSl.SlideNumber & ": " & oShp.TextFrame.TextRange.Text & vbCrLf
SomeoneSlides = SomeoneSlides & oSl.SlideNumber & ","
End If
End If
Next
Next
'we now have "search" unique slides.
MsgBox slideList
End Function
*** I note the following works as I want - leaving my in power points seeing highlight boxes around the slides 1,2,5
Dim r1 As SlideRange
Set r1 = ActivePresentation.Slides.Range(Array(1,2, 5)) 'this works
r1.Select
*** However, when i try to create this programmatically i fail (only highlighting the last slide in the array)
'Call SelectSlides("1,2,") '(output from the search)
Sub SelectSlides(YourSlideList As String)
Dim slideArr() As String
'Dim slideNum As Integer
Dim selAry As String
ActiveWindow.ViewType = PpViewType.ppViewNormal
ActiveWindow.Panes(1).Activate
slideArr = Split(YourSlideList, ",")
Dim r1 As SlideRange
For i = 0 To (UBound(slideArr) - 1)
slideNum = CInt(slideArr(i))
selAry = selAry & slideNum
'For all slides selected - modify as needed....
With ActivePresentation.Slides.Range(slideNum)
'Ignore the default background settings.
.FollowMasterBackground = False
'And add a new background color and effect.
.Background.Fill.PresetGradient msoGradientHorizontal, 1, msoGradientDaybreak
End With
Set r1 = ActivePresentation.Slides.Range(Array(slideNum)) 'this works
Next
r1.Select
End Sub
'///this is now working
Sub SelectSlides(YourSlideList As String)
Dim slideArr() As String
'Dim slideNum As Integer
Dim selAry As String
Dim selAry2(99) As Long
ActiveWindow.ViewType = PpViewType.ppViewNormal
ActiveWindow.Panes(1).Activate
slideArr = Split(YourSlideList, ",")
' slideArr2() = Split(YourSlideList, ",")
For i = 0 To (UBound(slideArr) - 1)
slideNum = CInt(slideArr(i))
selAry = selAry & slideNum
selAry2(i) = slideNum
'For all slides selected - modify as needed....
With ActivePresentation.Slides.Range(slideNum)
'Ignore the default background settings.
.FollowMasterBackground = False
'And add a new background color and effect.
.Background.Fill.PresetGradient msoGradientHorizontal, 1, msoGradientDaybreak
End With
Next
Dim r1 As SlideRange
Set r1 = ActivePresentation.Slides.Range(selAry2)
r1.Select
End Sub

Retrieve the page number of a picture

I would like to retrieve the number of the page a picture is on.
I know how to retrieve the picture using
ActiveDocument.Range.ShapeRange.LinkFormat.SourceFullName
but what variable holds the pagenumber of a picture?
https://word.tips.net/T000728_Determining_the_Current_Page_Number.html
CurPage = Selection.Information(wdActiveEndAdjustedPageNumber)
CurPage = Selection.Information(wdActiveEndPageNumber)
How about this?
Maybe you could change it to:
ActiveDocument.Range.ShapeRange.Information(wdActiveEndAdjustedPageNumber)
ActiveDocument.Range.ShapeRange.Information(wdActiveEndPageNumber)
Not tested as on a Linux machine right now!!
The following code will create a list of pictures including the page it is located on.
...
Sub LoopPages()
With ActiveDocument
Dim numPages As Integer: numPages = .Content.ComputeStatistics(wdStatisticPages)
Dim actPage As Integer
Dim rng As Range
Dim num As Integer
Dim FileOut As String: FileOut = "c:\Temp\Images\Pages.txt"
Open FileOut For Output As #1
For actPage = 1 To numPages
' Create a range of Page actPage
Set rng = .GoTo(What:=wdGoToPage, Name:=actPage)
Set rng = rng.GoTo(What:=wdGoToBookmark, Name:="\page")
For Each Shp In rng.ShapeRange
With Shp
If (.Type = msoLinkedPicture) Then
num = num + 1
Print #1, Format(num, "000") & " --> Page= " & actPage & " --> " & .LinkFormat.SourceFullName
End If
End With
Next Shp
For Each Shp In rng.InlineShapes
With Shp
If (.Type = wdInlineShapeLinkedPicture) Then
num = num + 1
Print #1, Format(num, "000") & " --> Page= " & actPage & " --> " & .LinkFormat.SourceFullName
End If
End With
Next Shp
Next actPage
MsgBox num
Close #1
End With
End Sub
...

Multiple images into excel using VBA

I have to write a script that parses the images from ppt and dumps into excel. To do this, I first export all the images in the slides to a folder and then call excel Application to import them into the worksheet. The following code, which I found online, with my modifications is as follows:
Sub ExtractImagesFromPres()
Dim oSldSource As Slide
Dim oShpSource As Shape
Dim Ctr As Integer
Dim ObjExcel As Object
Dim wb As Object
Dim ws As Object
Set ObjExcel = CreateObject("Excel.Application")
Dim sPath As String
sPath = "C:\Users\Aravind_Sampathkumar\Documents\Expor"
Ctr = 0
Set wb = ObjExcel.Workbooks.Open("C:\Users\Aravind_Sampathkumar\Documents\Book1.xlsx")
Set ws = wb.Sheets(1)
'Open oPres.Path & PathSep & "Book1.CSV" For Output As iFile
For Each oSldSource In ActivePresentation.Slides
For Each oShpSource In oSldSource.Shapes
If oShpSource.Type = msoPicture Then
' Hidden Export method
Call oShpSource.Export(sPath & "Img" & Format(Ctr, "0000") & ".JPG", ppShapeFormatJPG)
Ctr = Ctr + 1
End If
Next oShpSource
Next oSldSource
Folderpath = "C:\Users\Aravind_Sampathkumar\Documents\Expor"
Set fso = CreateObject("Scripting.FileSystemObject")
NoOfFiles = fso.GetFolder(Folderpath).Files.Count
Set listfiles = fso.GetFolder(Folderpath).Files
counter = 1
For Each fls In listfiles
strCompFilePath = Folderpath & "\" & Trim(fls.Name)
If strCompFilePath <> "" Then
If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
counter = counter + 1
' ws.Range("C" & counter).Value = fls.Name
ws.Range("D" & counter).ColumnWidth = 25
ws.Range("D" & counter).RowHeight = 100
ws.Range("D" & counter).Activate
'Call insert(strCompFilePath, counter)
ws.Shapes.AddPicture strCompFilePath, True, True, 100,100,70,70
End If
End If
Next
'ws.Shapes.AddPicture ("C:\Users\Aravind_Sampathkumar\Documents")
'With .ShapeRange
' .LockAspectRatio = msoTrue
' .Width = 100
'.Height = 100
'End With
' .Left = ws.Cells(i, 20).Left
'.Top = ws.Cells(i, 20).Top
'.Placement = 1
'.PrintObject = True
'End With
End Sub
When I run it, the images get dumped into excel but all the images are overlapped on each other in the same cell. Is there any way I can modify it such that images go into consecutive rows? 1 image per row?
This puts them a row apart but you would need to size them appropriately. Note I changed your paths for test paths.
Option Explicit
Sub ExtractImagesFromPres()
Dim oSldSource As Slide
Dim oShpSource As Shape
Dim Ctr As Integer
Dim ObjExcel As Object
Dim wb As Object
Dim ws As Object
Set ObjExcel = CreateObject("Excel.Application")
Dim sPath As String
sPath = "C:\Users\User\Desktop\TestFolder" '"C:\Users\Aravind_Sampathkumar\Documents\Expor"
Ctr = 0
Set wb = ObjExcel.Workbooks.Open("C:\Users\User\Desktop\TestFolder\Test.xlsx") '("C:\Users\Aravind_Sampathkumar\Documents\Book1.xlsx")
ObjExcel.Visible = True
Set ws = wb.Sheets(1)
For Each oSldSource In ActivePresentation.Slides
For Each oShpSource In oSldSource.Shapes
If oShpSource.Type = msoPicture Then
Call oShpSource.Export(sPath & "\" & "Img" & Format(Ctr, "0000") & ".JPG", ppShapeFormatJPG)
Ctr = Ctr + 1
End If
Next oShpSource
Next oSldSource
Dim Folderpath As String
Dim fso As Object
Dim NoOfFiles As Long
Dim listfiles As Object
Dim counter As Long
Dim fls As Variant
Dim strCompFilePath As String
Folderpath = "C:\Users\User\Desktop\TestFolder" '"C:\Users\Aravind_Sampathkumar\Documents\Expor"
Set fso = CreateObject("Scripting.FileSystemObject")
NoOfFiles = fso.GetFolder(Folderpath).Files.Count
Set listfiles = fso.GetFolder(Folderpath).Files
counter = 1
For Each fls In listfiles
strCompFilePath = Folderpath & "\" & Trim(fls.Name)
If strCompFilePath <> vbNullString Then
If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
counter = counter + 1
' ws.Range("C" & counter).Value = fls.Name
ws.Range("D" & counter).ColumnWidth = 25
ws.Range("D" & counter).RowHeight = 100
ws.Range("D" & counter).Activate
'Call insert(strCompFilePath, counter)
With ws.Pictures.Insert(strCompFilePath)
.Left = ws.Cells(counter, "D").Left
.Top = ws.Cells(counter, "D").Top
End With
End If
End If
Next
End Sub
Have a look at the documentation for the AddPicture method:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/shapes-addpicture-method-excel
expression.AddPicture(Filename, LinkToFile, SaveWithDocument, Left, Top, Width, Height)
Rather than adding the picture at the active cell, it's location is controlled by the Left and Top arguments. You can use the Left and Top properties of the target cell as the arguments of the AddPicture method:
ws.Shapes.AddPicture strCompFilePath, True, True, ws.Range("D" & counter).Left, ws.Range("D" & counter).Top,70,70
Here's a version that uses copy/paste instead of export/import - it does include the line to change the row height if you want to crib just that.. :P
Sub ExtractImagesFromPres()
Dim oSldSource As Slide
Dim oShpSource As Shape
Dim ObjExcel As Object
Dim wb As Object
Dim ws As Object
Set ObjExcel = CreateObject("Excel.Application")
Dim lOffset AS Long
Set wb = ObjExcel.Workbooks.Open("C:\Users\Aravind_Sampathkumar\Documents\Book1.xlsx")
Set ws = wb.Sheets(1)
'Open oPres.Path & PathSep & "Book1.CSV" For Output As iFile
lOffset = 5
For Each oSldSource In ActivePresentation.Slides
For Each oShpSource In oSldSource.Shapes
If oShpSource.Type = msoPicture Then
oShpSource.Copy
ws.Paste
With ws.Shapes(ws.Shapes.Count)
.Top = lOffset
.Left = 5
.Placement = 3 'xlFreeFloating
'This line sets the row height!
.TopLeftCell.EntireRow.RowHeight = 10 + .Height
lOffset = lOffset + .Height + 10
End With
End If
Next oShpSource
Next oSldSource
'Optional Tidy-Up code
'Set ws = Nothing
'wb.Save
'Set wb = Nothing
'ObjExcel.Quit
'Set ObjExcel = Nothing
End Sub
I'm 100% certain you can export the images from PPT directly to XLS, but I'm not really sure how to do that. However, since you are able to export those images from PPT into a folder, and you just need help importing the images from there, I thin the code below will do just what you want.
Sub InsertPics()
Dim fPath As String, fName As String
Dim r As Range, rng As Range
Application.ScreenUpdating = False
fPath = "C:\your_path_here\"
Set rng = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
i = 1
For Each r In rng
fName = Dir(fPath)
Do While fName <> ""
If fName = r.Value Then
With ActiveSheet.Pictures.Insert(fPath & fName)
.ShapeRange.LockAspectRatio = msoTrue
Set px = .ShapeRange
If .ShapeRange.Width > Rows(i).Columns(2).Width Then .ShapeRange.Width = Columns(2).Width
With Cells(i, 2)
px.Top = .Top
px.Left = .Left
.RowHeight = px.Height
End With
End With
End If
fName = Dir
Loop
i = i + 1
Next r
Application.ScreenUpdating = True
End Sub
' Note: you need the file extension, such as ',jpg', or whatever you are using, so you can match on that.
Sub Insert()
Dim strFolder As String
Dim strFileName As String
Dim objPic As Picture
Dim rngCell As Range
strFolder = "C:\Users\Public\Pictures\Sample Pictures\" 'change the path accordingly
If Right(strFolder, 1) <> "\" Then
strFolder = strFolder & "\"
End If
Set rngCell = Range("E1") 'starting cell
strFileName = Dir(strFolder & "*.jpg", vbNormal) 'filter for .png files
Do While Len(strFileName) > 0
Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
With objPic
.Left = rngCell.Left
.Top = rngCell.Top
.Height = rngCell.RowHeight
.Placement = xlMoveAndSize
End With
Set rngCell = rngCell.Offset(1, 0)
strFileName = Dir
Loop
End Sub

Workbook becomes corrupted and won't open after macro saves with certain number of sheets

In one excel instance (Instance A), my workbook (Workbook A) performs calculations based on user inputs and creates a worksheet with a chart object. This worksheet is copied and pasted into another workbook (Workbook B), which is closed in Instance A and then opened in a second excel instance (Instance B). Workbook B/Instance B are kept open and in a separate window, as the function of Workbook A/Instance A is to create worksheets to be viewed in Workbook B/Instance B.
So the macro process is: Worksheet is created in Instance A/Workbook A -> Workbook B is closed in Instance B -> Workbook B is opened in Instance A -> worksheet is copied from Workbook A to Workbook B -> Workbook B is saved/closed in Instance A -> Workbook B is opened in Instance B
In the interest of full disclosure, this is the entire sub:
Sub CopySSToNewWorkbook()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Dim MoveFromWkb As Workbook
Dim MoveFromSht As Worksheet
Dim ChartName As String
Dim RngToCover As Range
Dim duplicateChtPic As Shape
Dim NewSheetName As String
Dim TagString As String
If InputPage.Range("PanelTag") <> "" Then TagString = "-" & InputPage.Range("PanelTag").Text
Set MoveFromWkb = ThisWorkbook
'Set MoveFromSht = MoveFromWkb.Sheets("InputPage")
If InputPage.Range("PgNum") <> "" Then
NewSheetName = InputPage.Range("RoomNum").Text & TagString & " (Pg" & InputPage.Range("PgNum") & ")"
Set MoveFromSht = MoveFromWkb.Worksheets(NewSheetName)
Else
NewSheetName = InputPage.Range("RoomNum").Text & TagString
Set MoveFromSht = MoveFromWkb.Worksheets(NewSheetName)
End If
Set RngToCover = MoveFromSht.Range("E19:Y34")
ChartName = "Panel" & InputPage.Range("PgNum")
'Duplicate method
Set duplicateChtPic = MoveFromSht.ChartObjects(ChartName).Duplicate()
MoveFromSht.Shapes(ChartName).Delete
duplicateChtPic.ZOrder msoSendToBack
duplicateChtPic.Select
Call DelinkChartFromData
With duplicateChtPic
.height = RngToCover.height ' resize
.Width = RngToCover.Width ' resize
.top = RngToCover.top - 2 ' reposition
.Left = RngToCover.Left - 6 ' reposition
End With
MoveFromSht.Shapes("SaveSpoolSheetButton").Delete
MoveFromSht.Shapes("EditSpoolSheetButton").Visible = msoTrue
MoveFromSht.Shapes("UpdatePageNumberButton").Visible = msoTrue
MoveFromSht.Shapes("DeletePanelButton").Visible = msoTrue
Dim CNumber As String
Dim RelNum As String
Dim CrtNum As String
Dim Percentage As String
Dim SSFolderName As String
Dim Wkbname As String
Dim FileLocation As String
Dim Sht As Worksheet
Dim SSCopyYesNo As Integer
Dim DoubleSheet As Boolean
Dim MoveToWkb As Workbook
Dim MoveToSht As Worksheet
Dim PasteSheet As Worksheet
Dim CellName As name
Dim SheetCounter As Integer
SheetCounter = 1
Dim i As Integer
Dim varLinks As Variant
With InputPage
CNumber = .Range("JNumber").Text
CrtNum = "Crt" & .Range("CrateNum").Text
RelNum = "Rel" & .Range("RelNum").Text
Percentage = (.Range("RelPct").value * 100) & "Pct"
End With
If CNumber <> "" Then
Wkbname = Wkbname & CNumber
End If
If RelNum <> "Rel" Then
Wkbname = Wkbname & "_" & RelNum
End If
If CrtNum <> "Crt" Then
Wkbname = Wkbname & "_" & CrtNum
End If
If Percentage <> "0Pct" Then
Wkbname = Wkbname & "_" & Percentage
End If
SSFolderName = CreateSSFolders
FileLocation = SSFolderName & "\" & Wkbname & ".xlsb"
Dim newXL As Excel.Application
'Set newXL = GetObject(FileLocation).Application
If IsFileOpen(FileLocation) = True Then
Set newXL = GetObject(FileLocation).Application
newXL.Application.ScreenUpdating = False
newXL.DisplayAlerts = False
newXL.Application.Workbooks(Wkbname & ".xlsb").Close SaveChanges:=False
' newXL.Application.Quit
' Set newXL = Nothing
Else
Set newXL = CreateObject("Excel.Application")
newXL.Visible = True
End If
If FileFolderExists(FileLocation) Then
' newXL.Application.ScreenUpdating = False
' newXL.Application.DisplayAlerts = False
' On Error Resume Next
' newXL.Workbooks(Wkbname & ".xlsb").Close SaveChanges:=False
' On Error GoTo 0
Workbooks.Open FileLocation, UpdateLinks:=False, ReadOnly:=False
Set MoveToWkb = Workbooks(Wkbname & ".xlsb")
Else
Workbooks.Open (InputPage.MainFolderLocation.Text & "calc_and_trans\SpoolSheetWorkbookTemplate.xlsb")
Set MoveToWkb = Workbooks("SpoolSheetWorkbookTemplate.xlsb")
'if SSFolder doesn't already exist, the EditSpoolSheet module is imported to the new spoolsheet
'it is also exported to update any changes made
If FileFolderExists(InputPage.MainFolderLocation.Text & "calc_and_trans\ExportModules\EditSpoolSheet.bas") Then 'change path for home
MoveFromWkb.VBProject.VBComponents("EditSpoolSheet").export InputPage.MainFolderLocation.Text & "calc_and_trans\ExportModules\EditSpoolSheet.bas" 'change path for home
MoveToWkb.VBProject.VBComponents.Import InputPage.MainFolderLocation.Text & "calc_and_trans\ExportModules\EditSpoolSheet.bas" 'change path for home
Else
MoveFromSht.Shapes("EditSpoolSheetButton").Visible = msoFalse
MoveFromSht.Shapes("UpdatePageNumberButton").Visible = msoFalse
MoveFromSht.Shapes("CancelEditButton").Visible = msoFalse
MoveFromSht.Shapes("DeletePanelButton").Visible = msoFalse
End If
End If
For Each CellName In MoveToWkb.Names
If Right(CellName.name, 10) <> "Print_Area" Then
CellName.Delete
End If
Next
Dim NewPgNum As String
Dim OldPgNum As String
Dim startRead As Integer
Dim continueRun As Boolean
continueRun = False
NewPgNum = InputPage.Range("PgNum")
For Each Sht In MoveToWkb.Worksheets
startRead = InStr(Sht.name, "(Pg")
If Mid(Sht.name, startRead + 3) = (Right(MoveFromSht.name, Len(NewPgNum) + 1)) And DoubleSheet = False Then
DoubleSheet = True
Application.ScreenUpdating = True
SSCopyYesNo = MsgBox("Do you want to overwrite " & Sht.name & "?", vbYesNo + vbQuestion)
Application.ScreenUpdating = False
If SSCopyYesNo = vbYes Then
Dim spoolPosition As Integer
spoolPosition = Sht.Index
Sht.name = "_"
'attaching a macro to the edit spool sheet button
If FileFolderExists(InputPage.MainFolderLocation.Text & "calc_and_trans\ExportModules\EditSpoolSheet.bas") Then 'change path for home
MoveFromSht.Shapes("EditSpoolSheetButton").OnAction = "EditSpoolSheetClicked"
MoveFromSht.Shapes("UpdatePageNumberButton").OnAction = "UpdatePageNumberClicked"
MoveFromSht.Shapes("CancelEditButton").OnAction = "CancelEditButtonClicked"
MoveFromSht.Shapes("DeletePanelButton").OnAction = "DeletePanelButtonClicked"
End If
MoveFromSht.Range("Page_Number") = MoveFromSht.Range("AK21")
MoveFromSht.Copy After:=MoveToWkb.Sheets(spoolPosition)
Application.DisplayAlerts = False
Sht.Delete
Application.CutCopyMode = False
continueRun = True
End If
ElseIf DoubleSheet <> True Then
DoubleSheet = False
End If
SheetCounter = SheetCounter + 1
Next
If DoubleSheet = False Then
Set PasteSheet = Workbooks(MoveToWkb.name).Worksheets.Add
' MoveFromSht.Copy before:=MoveToWkb.Sheets(1)
'attaching a macro to the edit spool sheet button
If FileFolderExists(InputPage.MainFolderLocation.Text & "calc_and_trans\ExportModules\EditSpoolSheet.bas") Then 'change path for home
MoveFromSht.Shapes("EditSpoolSheetButton").OnAction = "EditSpoolSheetClicked"
MoveFromSht.Shapes("UpdatePageNumberButton").OnAction = "UpdatePageNumberClicked"
MoveFromSht.Shapes("CancelEditButton").OnAction = "CancelEditButtonClicked"
MoveFromSht.Shapes("DeletePanelButton").OnAction = "DeletePanelButtonClicked"
End If
MoveFromSht.Range("Page_Number") = MoveFromSht.Range("AK21")
MoveFromSht.Copy After:=MoveToWkb.Sheets(SheetCounter)
Application.CutCopyMode = False
continueRun = True
End If
If continueRun Then
For Each Sht In MoveToWkb.Worksheets
If Mid(Sht.name, 1, 5) = "Sheet" Then
Application.DisplayAlerts = False
Sht.Delete
End If
Next
Set MoveToSht = MoveToWkb.Sheets(MoveFromSht.name)
Dim moveToShtName As String
moveToShtName = MoveToSht.name
'fix in here
For Each CellName In MoveToWkb.Names
If Right(CellName.name, 10) <> "Print_Area" Then
Application.DisplayAlerts = False
CellName.Delete
End If
Next
Application.PrintCommunication = False
MoveToSht.DisplayPageBreaks = False
'For Each Sht In MoveToWkb.Worksheets
With MoveToSht.PageSetup
.PrintArea = "$A$1:$Z$36"
.Orientation = xlLandscape
.PaperSize = xlPaperLetter
.BlackAndWhite = True
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
.LeftMargin = Application.InchesToPoints(1.6)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0)
.BottomMargin = Application.InchesToPoints(0)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.CenterHorizontally = True
.CenterVertically = True
End With
Application.PrintCommunication = True
'%%%%%%%%new crate code %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'******************* Update Crate Sheet Info **************************************'
Dim crateSht As Worksheet
Dim frontSht As Worksheet
Set crateSht = MoveToWkb.Sheets("Crate_List")
Set frontSht = MoveToWkb.Sheets("FrontSheet")
Dim writeRow As Integer
Dim continueToEnd As Boolean
Dim roomColumn As Integer, pageColumn As Integer, sizeColumn As Integer, widthColumn As Integer, typeColumn As Integer, tagColumn As Integer
Dim infoTableCol As Integer
Dim colStep As Integer
For colStep = 1 To 15
Select Case crateSht.Cells(1, colStep).Text
Case "ROOM #"
roomColumn = colStep
Case "PAGE #"
pageColumn = colStep
Case "PANEL SIZE"
sizeColumn = colStep
Case "PANEL WIDTH"
widthColumn = colStep
Case "SQFT"
infoTableCol = colStep
Case "PANEL TYPE"
typeColumn = colStep
Case "PANEL TAG"
tagColumn = colStep
End Select
Next
'if first spoolsheet being added, set constant values (job name, job number etc.)
If MoveToWkb.Sheets.count = 3 Then
frontSht.Cells(5, 6) = MoveToSht.Range("AK2")
frontSht.Cells(6, 6) = MoveToSht.Range("AK3")
Dim EventsState As Boolean
EventsState = Application.EnableEvents
Application.EnableEvents = False
frontSht.Cells(6, 12) = MoveToSht.Range("AK7")
Application.EnableEvents = EventsState
End If
'determines where to write panel data: if row is blank, if Page # being written and read are both "" and panel tag/room # match, and if page numbers are not "" and match
For writeRow = 2 To 500
If Len(crateSht.Range("A" & writeRow).value) = 0 Or (InputPage.Range("PgNum") = "" And crateSht.Cells(writeRow, pageColumn).value = "" And crateSht.Range("A" & writeRow).value = InputPage.Range("RoomNum").value And _
crateSht.Cells(writeRow, tagColumn).value = InputPage.Range("PanelTag").value) Or (InputPage.Range("PgNum").value <> "" And _
InputPage.Range("PgNum").value = crateSht.Cells(writeRow, pageColumn).value) Then
'If continueToEnd Then
Exit For
End If
Next
Dim panelCrateData(24) As Variant
Dim panelTableData As Variant
panelTableData = MoveToSht.Range("AK1:AK39")
'writing spoolsheet information to crate sheet
With MoveToSht
If roomColumn <> 0 Then crateSht.Cells(writeRow, roomColumn) = panelTableData(22, 1) '.Range("AK22")
If pageColumn <> 0 Then crateSht.Cells(writeRow, pageColumn) = panelTableData(21, 1) '.Range("AK21")
If sizeColumn <> 0 Then crateSht.Cells(writeRow, sizeColumn) = panelTableData(13, 1) '.Range("AK13")
If widthColumn <> 0 Then crateSht.Cells(writeRow, widthColumn) = panelTableData(12, 1) ' .Range("AK12")
If tagColumn <> 0 Then crateSht.Cells(writeRow, tagColumn) = panelTableData(24, 1)
If typeColumn <> 0 Then crateSht.Cells(writeRow, typeColumn) = panelTableData(23, 1)
panelCrateData(0) = Round(CDbl(Replace(.Range("X35").Text, "SQFT", "")), 2)
panelCrateData(1) = panelTableData(15, 1) '.Range("AK15")
panelCrateData(2) = panelTableData(14, 1) '.Range("AK14")
panelCrateData(3) = panelTableData(17, 1) '.Range("AK17")
panelCrateData(4) = panelTableData(16, 1) '.Range("AK16")
panelCrateData(5) = panelTableData(18, 1) '.Range("AK18")
panelCrateData(6) = panelTableData(20, 1) '.Range("AK20")
panelCrateData(7) = panelTableData(19, 1) '.Range("AK19")
panelCrateData(8) = panelTableData(25, 1) '.Range("AK23")
panelCrateData(9) = panelTableData(26, 1) '.Range("AK24")
panelCrateData(10) = panelTableData(27, 1) '.Range("AK25")
panelCrateData(11) = panelTableData(29, 1) '.Range("AK27")
panelCrateData(12) = panelTableData(30, 1) '.Range("AK28")
panelCrateData(13) = panelTableData(31, 1) '.Range("AK29")
panelCrateData(14) = panelTableData(28, 1) '.Range("AK26")
panelCrateData(15) = panelTableData(34, 1) '.Range("AK32")
panelCrateData(16) = panelTableData(33, 1) '.Range("AK31")
panelCrateData(17) = panelTableData(35, 1) '.Range("AK33")
panelCrateData(18) = panelTableData(36, 1) '.Range("AK34")
panelCrateData(19) = panelTableData(37, 1) '.Range("AK35")
panelCrateData(20) = panelTableData(38, 1) '.Range("AK36")
panelCrateData(21) = panelTableData(39, 1) '.Range("AK37")
panelCrateData(22) = .Range("AU19")
'Holdback Info
panelCrateData(23) = .Range("AU12")
panelCrateData(24) = .Range("AU14")
'Additional Saddles
crateSht.Range(crateSht.Cells(writeRow, infoTableCol), crateSht.Cells(writeRow, infoTableCol + 24)) = panelCrateData ' "M" & writeRow & ":AK" & writeRow) = panelCrateData
End With
For writeRow = 2 To 500
If Len(crateSht.Range("A" & writeRow).value) = 0 Then ' Or crateSht.Range("A" & writeRow).value = InputPage.Range("RoomNum").value Then
'If continueToEnd Then
Exit For
End If
Next
Dim lastRow As Integer
lastRow = writeRow - 1
Dim totSqft As Double
totSqft = WorksheetFunction.Sum(crateSht.Range(crateSht.Cells(2, infoTableCol), crateSht.Cells(lastRow, infoTableCol))) '(crateSht 2:M" & lastRow))
Application.PrintCommunication = False
With crateSht
.PageSetup.PrintArea = "$A$1:$H$" & CStr(lastRow)
.PageSetup.PrintTitleRows = "$1:$1"
If lastRow = 2 Then .PageSetup.CenterHeader = "#" & MoveToSht.Range("AK3").value
.PageSetup.RightFooter = CStr(lastRow - 1) & " PANELS" & vbLf & "TOUCH UP KIT" & vbLf & "INTERCONNECTORS" _
& vbLf & "GLOVES" & vbLf & "T-BAR CLIPS" & vbLf & "INSULATION ON PANEL"
.PageSetup.RightHeader = CStr(totSqft) & " SQFT"
End With
Application.PrintCommunication = True
With frontSht
.Cells(11, 2) = lastRow - 1
.Cells(30, 2) = totSqft
End With
MoveToWkb.SaveAs filename:=FileLocation, FileFormat:=50
MoveToWkb.Close False
Set MoveToWkb = Nothing
'**********************************************************************************'
'Add new entry to recent panels table, unless room number already exists then replace that entry with the current info=
Call AddRecentPanelData
MoveFromSht.Delete
newXL.Application.ScreenUpdating = True
newXL.Application.DisplayAlerts = True
newXL.Application.AskToUpdateLinks = True
Application.Calculation = xlCalculationAutomatic
Set MoveFromWkb = Nothing
Set MoveFromSht = Nothing
Set MoveToSht = Nothing
newXL.Workbooks.Open FileLocation ', UpdateLinks:=False ', ReadOnly:=False
Set newXL = Nothing
Else
MoveToWkb.Close SaveChanges:=False
Set MoveToWkb = Nothing
newXL.Workbooks.Open FileLocation, UpdateLinks:=False, ReadOnly:=False
MoveFromSht.Delete
Application.Calculation = xlCalculationAutomatic
Set newXL = Nothing
Set MoveFromWkb = Nothing
Set MoveFromSht = Nothing
Set MoveToSht = Nothing
End If
Exit Sub
'#########################################################################################
ErrorHandler:
Dim Msg As String
If Err.number <> 0 Or Err.number <> 20 Then
Msg = "Error # " & Str(Err.number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
Call ReactiveUpdating
End Sub
So Workbook A uses this sub to create Workbook B/Instance B and save worksheets to it. The problem is, when Workbook A tries to add the 20th worksheet (sometimes 24th or 23rd but consistently in this area) there is an error in opening Workbook B in Instance B on this line (a couple scrolls up from the bottom) causing the code to break:
newXL.Workbooks.Open FileLocation, UpdateLinks:=False, ReadOnly:=False
Method 'Open' of object 'Workbooks' failed
If I click continue after this error pops up, it completes without an issue, but Workbook B in Instance B is corrupt. Also, if I click the X to close it Excel crashes, and Workbook B is corrupt/unable to open.
The strange thing is, it will always crash after the same number of worksheets are saved (between 20-23 worksheets). Even when I tried closing both workbooks and instances down completely after saving 19 times (just before the expected crash), saving the 20th worksheet still caused a crash.
This only started happening about a month ago, and it occurs on all the computers we have tested it on. We have even tested year old versions of the workbook, that certainly never had this issue, and they all have the same issue.
Please let me know if you can offer any help or need any more detail, any insight is greatly appreciated!
After a lot of work trying to change around the saving/opening process of the workbooks, I managed to figure out the issue. The workbook being saved (Workbook B) contained an ActiveX List Box control object, and after getting rid of it the issue went away. Hopefully this saves somebody the hours it took me to solve it!

how to export message body and data from Table to Excel from outlook 2010

I usually get Employee announcement in emails and I need to compile excel sheet from all these emails to know change in status of employee from previous line to current line .
Dear Concerned,
The change in status of the following employee has been carried out as per following details:
New Status
Change in Job
Effective Date
01-Feb-2015
Employee Name
Ricky ponting
Employee Code
4982
Designation
Sourcing Executive (Secondment)
Job Group
1A
Department
Sourcing & Supply Chain
Unit
Technology Sourcing
Division
Finance
Location
Islamabad
Reporting Line
Mr Micheal king
Note: Ricky Ponting was previously working as Tariff Implementation Support Officer in the org Communication dept and was reporting to Mr Robin Sing.
I need working code that export about HTML table data as well last Note : full line so that I can have an excel file of 2000 Employees whoes status have been changed and I can easily sort out from which previous line they were reporting to new line and I can get in touch with the new line for any Access rights re-authorization exercise on later stage .
Currently i am using following code thats working fine with the table extraction but NOTE: line is not being fetched with the following code based on following URL
https://techniclee.wordpress.com/2011/10/29/exporting-outlook-messages-to-excel/
Const MACRO_NAME = "Export Messages to Excel (Rev Sajjad)"
Private Sub ExportMessagesToExcel()
Dim olkFld As Outlook.MAPIFolder, _
olkMsg As Outlook.MailItem, _
excApp As Object, _
excWkb As Object, _
excWks As Object, _
arrCel As Variant, _
varCel As Variant, _
lngRow As Long, _
intPtr As Integer, _
intVer As Integer
Set olkFld = Session.PickFolder
If TypeName(olkFld) = "Nothing" Then
MsgBox "You did not select a folder. Operation cancelled.", vbCritical + vbOKOnly, MACRO_NAME
Else
intVer = GetOutlookVersion()
Set excApp = CreateObject("Excel.Application")
Set excWkb = excApp.Workbooks.Add
Set excWks = excWkb.Worksheets(1)
excApp.Visible = True
With excWks
.Cells(1, 1) = "Subject"
.Cells(1, 2) = "Received"
.Cells(1, 3) = "Sender"
.Cells(1, 4) = "New Status"
.Cells(1, 5) = "Effective Date"
.Cells(1, 6) = "Employee Name"
.Cells(1, 7) = "Employee Code"
.Cells(1, 8) = "Designation"
.Cells(1, 9) = "Job Group"
.Cells(1, 10) = "Department"
.Cells(1, 11) = "Unit"
.Cells(1, 12) = "Division"
.Cells(1, 13) = "Location"
.Cells(1, 14) = "Reporting Line"
.Cells(1, 15) = "Note:"
End With
lngRow = 2
For Each olkMsg In olkFld.Items
excWks.Cells(lngRow, 1) = olkMsg.Subject
excWks.Cells(lngRow, 2) = olkMsg.ReceivedTime
excWks.Cells(lngRow, 3) = GetSMTPAddress(olkMsg, intVer)
arrCel = Split(GetCells(olkMsg.HTMLBody), Chr(255))
For intPtr = LBound(arrCel) To UBound(arrCel)
Select Case Trim(arrCel(intPtr))
Case "New Status"
excWks.Cells(lngRow, 4) = arrCel(intPtr + 1)
Case "Effective Date"
excWks.Cells(lngRow, 5) = arrCel(intPtr + 1)
Case "Employee Name"
excWks.Cells(lngRow, 6) = arrCel(intPtr + 1)
Case "Employee Code"
excWks.Cells(lngRow, 7) = arrCel(intPtr + 1)
Case "Designation"
excWks.Cells(lngRow, 8) = arrCel(intPtr + 1)
Case "Job Group"
excWks.Cells(lngRow, 9) = arrCel(intPtr + 1)
Case "Department"
excWks.Cells(lngRow, 10) = arrCel(intPtr + 1)
Case "Unit"
excWks.Cells(lngRow, 11) = arrCel(intPtr + 1)
Case "Division"
excWks.Cells(lngRow, 12) = arrCel(intPtr + 1)
Case "Location"
excWks.Cells(lngRow, 13) = arrCel(intPtr + 1)
Case "Reporting Line"
excWks.Cells(lngRow, 14) = arrCel(intPtr + 1)
Case "Note:"
excWks.Cells(lngRow, 15) = arrCel(intPtr + 1)
End Select
Next
lngRow = lngRow + 1
Next
excWks.Columns("A:W").AutoFit
excApp.Visible = True
Set excWks = Nothing
Set excWkb = Nothing
Set excApp = Nothing
End If
Set olkFld = Nothing
End Sub
Private Function GetCells(strHTML As String) As String
Const READYSTATE_COMPLETE = 4
Dim IE As Object, objDoc As Object, colCells As Object, objCell As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "about:blank"
Do While IE.ReadyState <> 4: DoEvents: Loop
DoEvents
Set Doc = CreateObject("htmlfile")
IE.document.Body.innerHTML = strHTML
Set objDoc = IE.document
Set colCells = objDoc.getElementsByTagName("td")
If colCells.Length > 0 Then
For Each objCell In colCells
GetCells = GetCells & objCell.innerText & Chr(255)
Next
GetCells = Left(GetCells, Len(GetCells) - 1)
Else
GetCells = ""
End If
Set objCell = Nothing
Set colCells = Nothing
Set objDoc = Nothing
IE.Quit
Set IE = Nothing
End Function
Private Function GetSMTPAddress(Item As Outlook.MailItem, intOutlookVersion As Integer) As String
Dim olkSnd As Outlook.AddressEntry, olkEnt As Object
On Error Resume Next
Select Case intOutlookVersion
Case Is < 14
If Item.SenderEmailType = "EX" Then
GetSMTPAddress = SMTP2007(Item)
Else
GetSMTPAddress = Item.SenderEmailAddress
End If
Case Else
Set olkSnd = Item.Sender
If olkSnd.AddressEntryUserType = olExchangeUserAddressEntry Then
Set olkEnt = olkSnd.GetExchangeUser
GetSMTPAddress = olkEnt.PrimarySmtpAddress
Else
GetSMTPAddress = Item.SenderEmailAddress
End If
End Select
On Error GoTo 0
Set olkPrp = Nothing
Set olkSnd = Nothing
Set olkEnt = Nothing
End Function
Function GetOutlookVersion() As Integer
Dim arrVer As Variant
arrVer = Split(Outlook.Version, ".")
GetOutlookVersion = arrVer(0)
End Function
Function SMTP2007(olkMsg As Outlook.MailItem) As String
Dim olkPA As Outlook.PropertyAccessor
On Error Resume Next
Set olkPA = olkMsg.PropertyAccessor
SMTP2007 = olkPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001E")
On Error GoTo 0
Set olkPA = Nothing
End Function
Sub DebugLabels()
Dim olkMsg As Outlook.MailItem, objFSO As Object, objFil As Object, strBuf As String, strPth As String, arrCel As Variant, intPtr As Integer
strPth = Environ("USERPROFILE") & "\Documents\Debugging.txt"
Set olkMsg = Application.ActiveExplorer.Selection(1)
arrCel = Split(GetCells(olkMsg.HTMLBody), Chr(255))
For intPtr = LBound(arrCel) To UBound(arrCel)
strBuf = strBuf & StrZero(intPtr, 2) & vbTab & "*" & arrCel(intPtr) & "*" & vbCrLf
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFil = objFSO.CreateTextFile(strPth)
objFil.Write strBuf
objFil.Close
Set olkMsg = Application.CreateItem(olMailItem)
With olkMsg
.Recipients.Add "TechnicLee#earthlink.net"
.Subject = "Debugging Info"
.BodyFormat = olFormatPlain
.Body = "The debugging info for the selected message is attached. Please click Send to send this message to David."
.Attachments.Add strPth
.Display
End With
Set olkMsg = Nothing
Set objFSO = Nothing
Set objFil = Nothing
End Sub
Function StrZero(varNumber, intLength)
Dim intItemLength
If IsNumeric(varNumber) Then
intItemLength = Len(CStr(Int(varNumber)))
If intItemLength < intLength Then
StrZero = String(intLength - intItemLength, "0") & varNumber
Else
StrZero = varNumber
End If
Else
StrZero = varNumber
End If
End Function
A method of parsing text is described here: 17.2 Parsing text from a message body
Make the appropriate changes to look for "Note:"
Sub FwdSelToAddr()
Dim objOL As Outlook.Application
Dim objItem As Object
Dim objFwd As Outlook.MailItem
Dim strAddr As String
On Error Resume Next
Set objOL = Application
Set objItem = objOL.ActiveExplorer.Selection(1)
If Not objItem Is Nothing Then
strAddr = ParseTextLinePair(objItem.Body, "Email:")
If strAddr <> "" Then
Set objFwd = objItem.Forward
objFwd.To = strAddr
objFwd.Display
Else
MsgBox "Could not extract address from message."
End If
End If
Set objOL = Nothing
Set objItem = Nothing
Set objFwd = Nothing
End Sub
Function ParseTextLinePair _
(strSource As String, strLabel As String)
Dim intLocLabel As Integer
Dim intLocCRLF As Integer
Dim intLenLabel As Integer
Dim strText As String
intLocLabel = InStr(strSource, strLabel)
intLenLabel = Len(strLabel)
If intLocLabel > 0 Then
intLocCRLF = InStr(intLocLabel, strSource, vbCrLf)
If intLocCRLF > 0 Then
intLocLabel = intLocLabel + intLenLabel
strText = Mid(strSource, _
intLocLabel, _
intLocCRLF - intLocLabel)
Else
intLocLabel = _
Mid(strSource, intLocLabel + intLenLabel)
End If
End If
ParseTextLinePair = Trim(strText)
End Function