I am trying to copy text in Excel cells (cell A1 to A66) into a Word document. The goal of this operation is to copy it and paste it as TEXT. If copied directly from Excel, it will paste as a TABLE.
Private Sub Bouton1_Click()
Dim objWord As New Word.Application
With objWord
.Documents.Add
Application.Wait (Now + TimeValue("0:00:01") / 2)
Worksheets("Description2").Cells(1, 1).Copy
Application.Wait (Now + TimeValue("0:00:01") / 2)
.Selection.PasteSpecial xlPasteValues
.Visible = True
End With
Dim i As Integer
For i = 2 To 66
If Worksheets("Description2").Cells(i, 1) = Worksheets("Description2").Cells(i + 1, 1) Then Exit For
With objWord
Application.Wait (Now + TimeValue("0:00:01") / 2)
Worksheets("Description2").Cells(i, 1).Copy
Application.Wait (Now + TimeValue("0:00:01") / 2)
.Selection.PasteSpecial xlPasteValues
.Visible = True
End With
Next i
objWord.Application.Activate
objWord.Application.WindowState = wdWindowStateMaximize
End Sub
This code works about 70% of the time. When it doesn't work, I get this error (or a variation, but always concerning the clipboard):
Run-Time error "4605": This method or property is not available
because the clipboard is empty or not valid.
Also, sometimes a random OneDrive window opens.
I've added the Application.Wait lines to try to slow down the copy/paste, but it doesn't do that much.
How can I make my code more reliable?
If you want to paste as text, perhaps:
Sub CopyAsTextToWord()
Dim wordApp As New Word.Application
With wordApp
.Visible = True
.Documents.Add
Worksheets("Description2").Range("A1:A66").Copy
.Selection.PasteSpecial DataType:=wdPasteText
End With
End Sub
If on the other hand you want to paste each cell one at a time (this is what it seems like from your original code, not sure), perhaps a slightly different approach, avoiding the clipboard. Read the range into an array, iterate through it and then use Selection.TypeText to "paste" each element sequentially. Probably can be made more robust.
Sub TransferAsText()
Dim wordApp As New Word.Application
With wordApp
.Visible = True
.Documents.Add
Dim arr()
arr = Worksheets("Description2").Range("A1:A66").Value
Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
.Selection.TypeText Text:=CStr(arr(i, 1))
Next i
End With
End Sub
Write a separate function and capture all data from Excel
Function GetDataFromExcel()
CreateObject ("Excel.Application")
Dim xlApp As Excel.Application, xObjFD As FileDialog
Set xlApp = New Excel.Application
xlApp.Visible = True
Set xObjFD = Application.FileDialog(msoFileDialogFilePicker)
xObjFD.Title = "Select the excel file location " & FileType
With xObjFD
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm; *.xlsb", 1
.Show
' Selection is not null
If .SelectedItems.Count > 0 Then
xFilePath = .SelectedItems.Item(1)
Else
Exit Function
End If
Dim xlWorkBook As Object, valueCollected As String, _
rowCount As Integer : rowCount = 1
Set xlWorkBook = xlApp.Workbooks.Open(xFilePath, True, False)
xlWorkBook.Activate
Set ArrayValues = New ArrayList
loopToCollectData:
On Error GoTo err
valueCollected = xlApp.ActiveWorkbook.Sheets("Description2").Range("A" & rowCount).Value
If valueCollected <> "" Then
ArrayValues.Add valueCollected
If rowCount < 66 then
rowCount = rowCount + 1
GoTo loopToCollectData
End If
End If
End With
xlWorkBook.Close
xlApp.Visible = False
Exit Function
err:
xlWorkBook.Close
xlApp.Visible = False
MsgBox "Please select the relevant input file!"
End
End Function
Once data is collected, then it is independent of the application and could be used inside the word application.
An Array could be also used to collect the data by using the range.
Function GetDataFromExcel()
' Some Code ===========
dataArrayCollected = Application.Transpose(Range(Cells(1, 1), Cells(66, 1)))
' Some more Code ===========
' No more code =========== 😃 😁
End Function
Related
I have an excel file that I need to do a find and replace and the cells have formatting already. I need to retain the formatting. When I do an ordinary find and replace in excel, this removes the formatting. I need help to retain the formatting. I searched online and found the below link but this code is not working for me.
When I try the below code, this line is red in the code.
Call CharactersReplace(xRg, "<span style="background-color: #ffff00;">KK</span>", "<span style="background-color: #ffff00;">Kutools</span>", True)
I need help to correct this code and get this to work. Or if there is an easier way to do this, please let me know.
https://www.extendoffice.com/documents/excel/3760-excel-find-and-replace-preserve-formatting.html
Sub CharactersReplace(Rng As Range, FindText As String, ReplaceText As String, Optional MatchCase As Boolean = False)
'UpdatebyExtendoffice20160711
Dim I As Long
Dim xLenFind As Long
Dim xLenRep As Long
Dim K As Long
Dim xValue As String
Dim M As Long
Dim xCell As Range
xLenFind = Len(FindText)
xLenRep = Len(ReplaceText)
If Not MatchCase Then M = 1
For Each xCell In Rng
If VarType(xCell) = vbString Then
xValue = xCell.Value
K = 0
For I = 1 To Len(xValue)
If StrComp(Mid$(xValue, I, xLenFind), FindText, M) = 0 Then
xCell.Characters(I + K, xLenFind).Insert ReplaceText
K = K + xLenRep - xLenFind
End If
Next
End If
Next
End Sub
Sub Test_CharactersReplace()
Dim xRg As Range
Dim xTxt As String
Dim xCell As Range
On Error Resume Next
If ActiveWindow.RangeSelection.Count > 1 Then
xTxt = ActiveWindow.RangeSelection.AddressLocal
Else
xTxt = ActiveSheet.UsedRange.AddressLocal
End If
Set xRg = Application.InputBox("Select a range:", "Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
Call CharactersReplace(xRg, "<span style="background-color: #ffff00;">KK</span>", "<span style="background-color: #ffff00;">Kutools</span>", True)
End Sub
I appreciate what I learned from the comment by #Marc but after trying to edit the xml, I found it was just too complicated. Any little mistake I made rendered the xml file unopenable by Excel.
So my solution was to copy the sheet into Word (it comes in as a Word table), using Word's Advanced Find and Replace features, and then pasting the table back into the Excel sheet. It worked for me.
Because I had lot of sheets I wanted to do this with, I made this VBA routine. After copying my data (in the first 2 columns) into Word, it removes all superscripted characters, plus does some formatting I needed. Not pretty but it worked to do 72 sheets for me, saving a lot of tedious work.
Sub ExcelSheetsEditedViaWord()
' note: must add a reference to the Word-library (Microsoft Word 16.0 Object Lilbrary)
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim s As String, i As Integer, sh As Worksheet, r As Range
Application.DisplayStatusBar = True
Application.StatusBar = "Opening Word ..."
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
With ActiveDocument.PageSetup
.PageWidth = InchesToPoints(11)
.PageHeight = InchesToPoints(22)
End With
wrdApp.ActiveWindow.ActivePane.View.Zoom.Percentage = 40
i = 0
For Each sh In ThisWorkbook.Worksheets
Set r = sh.Range("A1:B1")
Set r = sh.Range(r, r.End(xlDown))
r.Copy
'wait to avoid error that sometimes stops code.
Application.Wait (Now + TimeValue("0:00:01"))
wrdDoc.Range.PasteExcelTable False, False, False
sh.Activate
sh.Range("A1").Select
With wrdApp.Selection
.Find.ClearFormatting
With .Find.Font
.Superscript = True
.Subscript = False
End With
.Find.Replacement.ClearFormatting
With .Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
.Find.Execute Replace:=wdReplaceAll
.WholeStory
.Cut
'wait some second to try to avoid error that stops code. However,
'even when code stops, hitting debug allows it to continue
Application.Wait (Now + TimeValue("0:00:06"))
sh.Paste
With sh.Columns("A:B")
.VerticalAlignment = xlTop
.WrapText = True
.Font.Name = "Times New Roman"
.Font.Size = 16
End With
i = i + 1
End With
Application.StatusBar = i & " sheets done"
Next sh
wrdApp.Quit False ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
MsgBox i & " sheets of the workbook processed"
End Sub
I have some Application.Wait() statements where the code would fail occasionally -- something I've seen a lot with code that copy/pastes between Excel and Word. But when it fails, clicking debug and continuing works every time. As I said, not pretty but gets the job done.
I am searching for a string in a table inside a PDF file using a VBA script. The script is working when called from Word but not when called from Excel.
My PDF has many tables and the goal is to get the table number of the table containing a specific string.
Sub FindTableno()
Dim oTbl As Table
Dim oRow As Row
Dim oCell As Cell
Dim tblno As Integer
On Error Resume Next
' Create a "FileDialog" object as a File Picker dialog box.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim sfileName As String
With fd
.AllowMultiSelect = False
.Filters.Clear
.Title = "Select a PDF File"
.Filters.Add "All PDF Documents", "*.pdf?", 1
If .Show = True Then
sfileName = Dir(.SelectedItems(1)) ' Get the file.
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If Trim(sfileName) <> "" Then
Dim objWord As Object ' Create a Word object.
Set objWord = CreateObject("Word.Application")
objWord.Visible = False ' Do not show the file.
' Create a Document object and open the Word file.
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Open(FileName:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
' Search within tables in selected PDF file
objDoc.Activate
If ActiveDocument.Tables.Count > 0 Then
tblno = 1
For Each oTbl In ActiveDocument.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
oCell.Select
Selection.Find.Execute FindText:="Nutrition Information"
If Selection.Find.Found = True Then
MsgBox (tblno)
Exit Sub
Else
End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & ActiveDocument.Tables.Count)
End If
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
End Sub
The main issue is in this part where you use oCell.Select and afterwards Selection.Find. In this case Selection refers to the selected cell in Excel! This is because you didn't specifiy any relation to Word here, so Excel assumes you mean the selected cell in Excel.
I recommend to read How to avoid using Select in Excel VBA. The same is valid for Word VBA code.
Also don't use .Activate or you will get a similar issue. Always reference the worksheet or document directly:
If objDoc.Tables.Count > 0 Then
tblno = 1
For Each oTbl In objDoc.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
oCell.Range.Find.Execute FindText:="Nutrition Information"
If oCell.Range.Find.Found = True Then
MsgBox (tblno)
Exit Sub
End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & objDoc.Tables.Count)
Thanks #Pᴇʜ, this worked for me
Sub FindTableno()
Dim oTbl As Table
Dim oRow As Row
Dim oCell As Cell
Dim tblno As Integer
' Create a "FileDialog" object as a File Picker dialog box.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim sfileName As String
With fd
.AllowMultiSelect = False
.Filters.Clear
.Title = "Select a PDF File"
.Filters.Add "All PDF Documents", "*.pdf?", 1
If .Show = True Then
sfileName = Dir(.SelectedItems(1)) ' Get the file.
End If
End With
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Trim(sfileName) <> "" Then
Dim objWord As Object ' Create a Word object.
Set objWord = CreateObject("Word.Application")
objWord.Visible = True ' Do not show the file.
' Create a Document object and open the Word file.
Dim objDoc As Word.Document
'Set objDoc = objWord.Documents.Open(Filename:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
Set objDoc = objWord.Documents.Open(Filename:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
' Search within tables in selected PDF file
If objDoc.Tables.count > 0 Then
tblno = 1
For Each oTbl In objDoc.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
pos = InStr(oCell.Range.Text, "Nutrition Information ")
If pos <> 0 Then
GoTo line1
End If
'Else
'End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & objDoc.Tables.count)
'MsgBox (oCell.Range.Text)
End If
line1:
MsgBox (tblno)
End Sub
I've been wrestling with using Excel to create PowerPoint slide using a .potx file as the powerpoint template.
The problem I have is that I am not able to figure out how to duplicate the slidemaster so I can use custom layouts.
I want a new presentation created that uses the layouts defined in the .potx file?
I'm brand new to VBA so my code is a little rough on the edges.
Sub ExcelRangeToPowerPoint()
'PURPOSE: Copy/Paste An Excel Range Into a New PowerPoint Presentation
'SOURCE: www.TheSpreadsheetGuru.com
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim mytextbox As Object
Dim Ws As Worksheet
Dim trueranges As New Collection 'Store the ranges to be used in master excel file
Dim start_counting_from_this_row_number As Integer 'starting value of rows to search for TRUE/FALSE
Dim worksheetnames As New Collection 'collect all worksheet names if TRUE
Dim rg As Range
Const PXLtoINCH As Single = 72# 'PP uses pixels not inches, this is the conversion factor
Dim SQPOSITION As Double
Dim SQHeight As Double
Dim range_shape As New WSOrgDisplayAttributes
Dim all_data As New Collection
'*******************************************************************************************************************
'Check to see if Master Data Sheet Spreadsheet is in same directory and if so, open it.
Dim FilePath As String
Dim FileNameOnly As String
FileNameOnly = "WS Asset Availability Master Data Spreadsheet.xlsx"
FilePath = ActiveWorkbook.Path & "\" & FileNameOnly
If IsFile(FilePath) = True Then 'ENDIF is near the end of the SUB
If CheckFileIsOpen(FileNameOnly) = False Then
Workbooks.Open (FileName)
MsgBox ("A small time Delay...(This ensures file is open and ready for use")
Application.Wait (Now + TimeValue("00:00:10")) 'this allows time to open before other parts of macro run
End If
'*******************************************************************************************************************
'*******************************************************************************************************************
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(Class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(Class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
myPresentation.ApplyTemplate (ThisWorkbook.Path & "\" & "SRR Template.potx")
'myPresentation.ApplyTemplate (FilePath & "\" & "SRR Template.potx")
'*******************************************************************************************************************
'*******************************************************************************************************************
'Initialize variables
start_counting_from_this_row_number = 3 'Find row where first TRUE/FALSE is under column "D"
Set rg = ThisWorkbook.Sheets("SRR Helper").Range("D1").CurrentRegion 'count the max rows
SQPOSITION = 6 'inches
SQHeight = 0.18 'inches
'*******************************************************************************************************************
'*******************************************************************************************************************
'Push all TRUE's to collections
'ADD HEADER INFO LATER
For x = start_counting_from_this_row_number To rg.Rows.Count
If ThisWorkbook.Sheets("SRR Helper").Range("D" & x).Value = True Then
Set range_shape = Nothing
range_shape.let_range_check = True
range_shape.let_shape_range = ThisWorkbook.Sheets("SRR Helper").Range("C" & x).Value
range_shape.let_sheet_name = ThisWorkbook.Sheets("SRR Helper").Range("E" & x).Value
all_data.Add range_shape
End If
Next x
'*******************************************************************************************************************
'*******************************************************************************************************************
'Iterate through collections to push Master File to PP presenation
Dim iterator As New WSOrgDisplayAttributes
Dim iterator2 As New WSOrgDisplayAttributes
Set mySlide = myPresentation.Slides.Add(1, 1) 'Always create at least one slide myPresentation.Designs(1).SlideMaster.CustomLayouts (GetLayoutIndexFromName("SRRLayout", myPresentation.Designs(1)))
myPresentation.PageSetup.SlideSize = ppSlideSizeOnScreen 'Set slide orientation and size
Dim sheet_counter As Integer
sheet_counter = 1
Dim updateslide As Boolean
Dim temp As Double
temp = (SQPOSITION) * PXLtoINCH
For i = 1 To all_data.Count
'Set Worksheet
Set iterator = all_data(i)
Set iterator2 = Nothing
If all_data.Count = 1 Then
updateslide = False 'only one sheet so no need for new slide, they are equal
Else
If i = all_data.Count Then ' last element can't be compared with the next, but can be compared to previous
Set iterator2 = all_data(i - 1)
If iterator2.get_sheet_name = iterator.get_sheet_name Then
updateslide = False
Else
updateslide = True
sheet_counter = sheet_counter + 1
End If
Else
Set iterator2 = all_data(i + 1)
If iterator2.get_sheet_name = iterator.get_sheet_name Then
updateslide = False
Else
updateslide = True
sheet_counter = sheet_counter + 1
End If
End If
End If
Set Ws = Workbooks("WS Asset Availability Master Data Spreadsheet.xlsx").Sheets(iterator.get_sheet_name)
'Copy Range from Excel
Set rg = Ws.Range(iterator.get_shape_range)
'Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
Application.Wait (Now + TimeValue("00:00:1"))
'Copy Excel Range
rg.Copy
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile
Set myShape = mySlide.Shapes(mySlide.Shapes.Count) 'Control the latest shape to be pasted
'Set position:
myShape.LockAspectRatio = msoTrue
myShape.Height = 0.62 * PXLtoINCH
myShape.Width = 9.74 * PXLtoINCH
myShape.Left = 0.14 * PXLtoINCH
myShape.Top = temp
temp = myShape.Top + myShape.Height
If updateslide = True Then
temp = (SQPOSITION) * PXLtoINCH ' reset temp back to starting position.
End If
'Add a slide to the Presentation - only if new sheetname
If updateslide = True Then
Set mySlide = myPresentation.Slides.Add(sheet_counter, 2) '11 = ppLayoutTitleOnly
updateslide = False
temp = (SQPOSITION) * PXLtoINCH
End If
Next i
'*******************************************************************************************************************
'*******************************************************************************************************************
'Make PowerPoint Visible and Active
PowerPointApp.Visible = True
PowerPointApp.Activate
'Clear The Clipboard
Application.CutCopyMode = False
'*******************************************************************************************************************
'*******************************************************************************************************************
Else
MsgBox ("File Does not Exist in local directory - WS Asset Availability Master Data Spreadsheet.xlsx")
End If
End Sub
Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
On Error Resume Next
IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function
Function CheckFileIsOpen(chkSumfile As String) As Boolean
On Error Resume Next
CheckFileIsOpen = (Workbooks(chkSumfile).Name = chkSumfile)
On Error GoTo 0
End Function
Function GetLayoutIndexFromName(sLayoutName As String, oDes As Design) As Long
Dim x As Long
For x = 1 To oDes.SlideMaster.CustomLayouts.Count
If oDes.SlideMaster.CustomLayouts(x).Name = sLayoutName Then
GetLayoutIndexFromName = x
Exit Function
End If
Next
End Function
I've tried something similar to this:
Set kitap = CreateObject("Excel.Application")
If IsXlsOpen() = True Then
kitap.Application.Quit
End If
.. but didnt work out so I neeed to find how to close all excel files before starting my program in vb6
EDIT: Full code here:
Dim i As Integer
Dim kitap As Object
Dim strcnn As String
Dim cnn As New ADODB.Connection
Dim Cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Private Sub Form_Load()
strcnn = "myconn"
cnn.Open strcnn
Cmd.ActiveConnection = cnn
End Sub
Public Function dotdate(ByRef elem) As String
Dim day, month, year As String
year = Right(elem, 4)
month = Mid(elem, Len(elem) - 5, 2)
day = Mid(elem, 1, Len(elem) - 6)
If Len(day) = 1 Then
day = "0" & day
End If
dotdate = day & "." & month & "." & year
End Function
Public Function IsXlsOpen(wbName) As String
Dim xl As Excel.Application
IsXlsOpen = False
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
If Err.Number <> 0 Then Exit Function
xl.Workbooks(wbName).Activate
If Err.Number = 0 Then IsXlsOpen= True
End Function
Private Sub Command1_Click()
Dim i As Integer
Dim cek As String
Set kitap = CreateObject("Excel.Application")
If IsXlsOpen("my.xls") = True Then
kitap.Application.Quit
End If
kitap.Workbooks.Add
cek = "Select * From blabla"
rs.Open cek, cnn
If rs.EOF = True Then
Situation.Caption = "Situation : EOF"
Else
kitap.Cells(i + 1, 1).Value = "ID"
kitap.Cells(i + 1, 2).Value = "Caption"
kitap.Cells(i + 1, 3).Value = "Date"
i = i + 1
Do While Not rs.EOF
kitap.Cells(i + 1, 1).Value = rs.Fields("id")
kitap.Cells(i + 1, 2).Value = rs.Fields("capt")
kitap.Cells(i + 1, 3).Value = dotdate(rs.Fields("date"))
rs.MoveNext
i = i + 1
Loop
rs.Close
End If
kitap.ActiveWorkbook.SaveAs (App.Path & "\my.xls")
kitap.Application.Quit
Situation.Caption = "Situation : Excel Formatted Report Ready."
Exit Sub
err:
rs.Close
Situation.Caption = "Critical Error! : Connection error detected. Please reset action."
End Sub
While I'm more a vbscript and vba guy, a bit more info would help:
ie what is IsXlsOpen?
what is your full kitmap code, ie have you opened and closed workbooks?
do you have any other xl instances open (before or during your code)?.
this link often solves VBA issues, in fixing global references
Note that it is good practice to close/quit workbooks/instances and set them to Nothing, ie in Tushar's code
xlWB.Close False
xlApp.Quit
Set xlWB = Nothing
Set xlApp = Nothing
To save and close all workbooks, read more
Option Explicit
Sub CloseAndSaveOpenWorkbooks()
Dim Wkb As Workbook
With Application
.ScreenUpdating = False
' Loop through the workbooks collection
For Each Wkb In Workbooks
With Wkb
' if the book is read-only
' don't save but close
If Not Wkb.ReadOnly Then
.Save
End If
' We save this workbook, but we don't close it
' because we will quit Excel at the end,
' Closing here leaves the app running, but no books
If .Name <> ThisWorkbook.Name Then
.Close
End If
End With
Next Wkb
.ScreenUpdating = True
.Quit 'Quit Excel
End With
End Sub
I need to take a word document and export its paragraphs (hard breaks) into single cells in a excel spreadsheet keeping bullet numbers and letters along with the text, tables and diagrams.
I assume VBA would be the best approach.
I am using office 2007.
Something like this?
Sub ReadContenttoExcel()
Dim DocPara As Paragraph
' work with the new excel workbook
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
Dim xxRow, xxCol As Integer
'specify the workbook to work on
WorkbookToWorkOn = "D:\test.xlsx"
xxRow = 1
xxCol = 1
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
Set oSheet = oWB.Sheets(1)
oSheet.Activate
' Parameters for testing -- see whats happening
With oXL
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
.Visible = True
End With
'Run through the Document and Save each of the Heading 1 Texts to Excel
For Each DocPara In ActiveDocument.Paragraphs
Select Case (DocPara.Range.Style)
Case "Heading 1"
'Debug.Print "Heading1~" & Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
xxRow = xxRow + 1
oSheet.Cells(xxRow, 1).Value = Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
Case "Heading 2"
oSheet.Cells(xxRow, 2).Value = Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
Case "Heading 3"
oSheet.Cells(xxRow, 3).Value = Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
Case "Heading 4"
oSheet.Cells(xxRow, 4).Value = Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
Case Else
oSheet.Cells(xxRow, 5).Value = Left(DocPara.Range.Text, Len(DocPara.Range.Text) - 1)
End Select
xxRow = xxRow + 1
Next
ActiveWorkbook.Save
If ExcelWasNotRunning Then
oXL.Quit
End If
'Realease the Object References
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing
End Sub
Save as .htm then open with excell.