This code exports the Range as .jpg to a location that is attached to an email with another module running this.
Sub Export_Dashboard_To_PC()
Dim fileSaveName As Variant, pic As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FName = ThisWorkbook.Path & "\Dashboard.jpg"
With ThisWorkbook.Sheets("Dashboard")
Sheets("Dashboard").Range(Sheets("BP").Range("AE4")).CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set sht = Sheets.Add
sht.Shapes.AddChart
sht.Shapes.Item(1).Select
Set objChart = ActiveChart
With objChart
.ChartArea.Height = Sheets("Dashboard").Range(Sheets("BP").Range("AE4")).Height
.ChartArea.Width = Sheets("Dashboard").Range(Sheets("BP").Range("AE4")).Width
.ChartArea.Fill.Visible = msoFalse
.ChartArea.Border.LineStyle = xlLineStyleNone
.Paste
.Export Filename:=FName, FilterName:="jpg"
End With
sht.Delete
End With
ActiveSheet.Cells(1, 1).Select
Sheets("BP").Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
It all happens in one and sometimes the code exports the image as a blank and attach it as a blank on the email and sends it. I can see the problem is at the export because when I go to the location of the export and open the .jpg, it shows a blank.
I have stepped through it many times, every time it works.
DoEvents gives me the same results.
I have this kind of routine in my commercial Excel add-in, and I've had to overengineer the stuffing out of it. So I started with your code, cleaned it up a bit (it wouldn't compile with Option Explicit set), and inserted some lines to (a) try to make it work, and (b) figure out where it got hung up. Part of what I did was build the copy/paste into a loop, to get more feedback faster.
Sub Export_Dashboard_To_PC()
' turn these off for testing
'Application.ScreenUpdating = False
'Application.DisplayAlerts = False
Dim RangeToCopy As Range
' fully qualify the ranges
Set RangeToCopy = ThisWorkbook.Worksheets("Dashboard"). _
Range(ThisWorkbook.Worksheets("BP").Range("AE4").Text)
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets.Add
'DoEvents ' sometimes needed after Worksheets.Add but apparently not this time
Dim ImgNumber As Long
For ImgNumber = 1 To 20
Dim FName As String
FName = ThisWorkbook.Path & "\Dashboard" & ImgNumber & ".png"
' PNG much better image format than JPG for worksheet images (crisper, half the size)
Dim cht As Chart
Set cht = wks.Shapes.AddChart(, wks.Columns(ImgNumber).Left, wks.Rows(ImgNumber).Top).Chart
' inserted .left and .top so I could see individual charts
'DoEvents ' sometimes needed after Shapes.AddChart but apparently not here
With cht
With .ChartArea
.Height = RangeToCopy.Height
.Width = RangeToCopy.Width
.Fill.Visible = msoFalse
.Border.LineStyle = xlLineStyleNone
End With
DoEvents ' inserted because sometimes Range.CopyPicture throws an error
RangeToCopy.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
' copy as bitmap here, more reliable, rather than convert to bitmap during export
Dim iLoop As Long, MaxLoop As Long
MaxLoop = 10
For iLoop = 1 To MaxLoop
DoEvents ' inserted b/c sometimes clipboard is slow to contain copied object
.Paste
If .Shapes.Count > 0 Then
' yay, image pasted into chart
Debug.Print iLoop
Exit For
End If
If iLoop >= MaxLoop Then
' boo, never succeeded
MsgBox "Export Picture Failed", vbCritical
GoTo ExitSub
End If
Next
'DoEvents
.Export Filename:=FName, FilterName:="png"
'DoEvents
'.Parent.Delete ' don't delete, examine after run
End With
Next
ExitSub:
'wks.Delete ' don't delete, examine after run
ActiveSheet.Cells(1, 1).Select
ThisWorkbook.Worksheets("BP").Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
So what I learned was where I needed to put the DoEvents, and where the big bottleneck occurs. The big bottleneck is getting the range copied into the clipboard. VBA starts the copy, and sometimes the copy takes longer than VBA takes to get to the paste, and VBA isn't patient enough to wait. DoEvents is supposed to make VBA wait, but it doesn't always work that way. If the clipboard is still empty (doesn't yet contain a copy of the range), then nothing is pasted, and the exported chart is blank.
So I put another loop after the copy, and did the paste inside the loop. After the paste, if the chart contained an object, then the paste must have worked, so I proceeded to the export.
Usually (in 14 of 20 big loops) the paste resulted in a shape being added to the chart in the first small loop, but in 2/20, it took as many as 6 or 7 small loops.
So for the final code, this is what I came up with. I had to insert
Application.ScreenUpdating True
before the copy, otherwise the copied range was always blank (a blank shape was pasted into the chart.
Sub Export_Dashboard_To_PC()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim RangeToCopy As Range
' fully qualify the ranges
Set RangeToCopy = ThisWorkbook.Worksheets("Dashboard"). _
Range(ThisWorkbook.Worksheets("BP").Range("AE4").Text)
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets.Add
Dim FName As String
FName = ThisWorkbook.Path & "\Dashboard_" & Format(Now, "hhmmss") & ".png"
' PNG much better image format than JPG for worksheet images (crisper, half the size)
Dim cht As Chart
Set cht = wks.Shapes.AddChart.Chart
With cht
With .Parent
.Height = RangeToCopy.Height
.Width = RangeToCopy.Width
End With
With .ChartArea
.Fill.Visible = msoFalse
.Border.LineStyle = xlLineStyleNone
End With
ThisWorkbook.Worksheets("Dashboard").Activate
Application.ScreenUpdating = True ' otherwise copied region blank
DoEvents ' inserted because sometimes Range.CopyPicture throws an error
RangeToCopy.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
Application.ScreenUpdating = False
Dim iLoop As Long, MaxLoop As Long
MaxLoop = 10
For iLoop = 1 To MaxLoop
DoEvents ' inserted b/c sometimes clipboard is slow to contain copied object
.Paste
If .Shapes.Count > 0 Then
' yay, image pasted into chart
Exit For
End If
If iLoop >= MaxLoop Then
' never succeeded
MsgBox "Export Picture Failed", vbCritical
GoTo ExitSub
End If
Next
.Export Filename:=FName, FilterName:="png"
End With
ExitSub:
wks.Delete
ActiveSheet.Cells(1, 1).Select
ThisWorkbook.Worksheets("BP").Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Follow Up
In my production code (which I checked after posting this), I don't ever set
Application.ScreenUpdating = False
I also don't insert a new sheet, instead I put my temporary chart on the active sheet, which contains the range I'm exporting.
And my internal loop is
With .chart
Do Until .Pictures.Count = 1
DoEvents
.Paste
Loop
.Export sExportName
End With
Same thing, except it assumes it will never never get into an infinite loop.
I experienced a similar problem when using VBA to paste an image into a chart object and export it as a jpg file. I noticed there were no issues when I slowly stepped through the code line by line. Additionally, there were no issues when I added a comment box after pasting the image but before exporting as a jpg, forcing the code to pause. This led me to believe the problem was with Excel not having sufficient time to complete the paste procedure before exporting the image file.
I solved the issue by adding a 3-second loop between pasting and exporting. I also turned on Screen Updating.
Dim time1, time2
time1 = Now
time2 = Now + TimeValue("0:00:03")
Do Until time1 >= time2
DoEvents
time1 = Now()
Loop
Related
i have a working code from a previeous thread in here, but i would like to see if there are any possibillities to change/ rework the code so when i copy the sheet from the main workbook to new sheet that the images thats in the sheet will be small images that stay in the sheet. Today i need either to have the images in a folder or access to internet "if using url" to see the images. I would like to be able to see the images if i change pc or are offline etc.
The old thread is her : Rename or add macro to module in a copied sheet from main workbook with vba
Here is the code i use for copying the sheet:
Dim sh As Shape, wbNew As Workbook, ws As Worksheet
ThisWorkbook.Sheets("Import").Copy
Set wbNew = ActiveWorkbook
Set ws = wbNew.Sheets("Import")
For Each sh In ws.Shapes
'relink only if has action set
If Len(sh.OnAction) > 0 Then
sh.OnAction = ws.CodeName & ".Zoom_Click"
End If
Next sh
Adding some more info here:
This code below are the one i use to import the pictures and i guess this is the reason the images are not showing when i use the workbook og t.eg another pc without internet. From what i understand the images here are imported as shapes/objects and its linked to the image files instead of actually have the image within the woorkbook, am i correct here?
This is from the main Workbook where i use the coda above to copy from.
Private Sub CommandButton2_Click()
Dim theShape As shape
Dim xRg As Range
Dim xCol As Long
On Error Resume Next
Application.ScreenUpdating = False
Set rng = Worksheets("Import").Range("A4:B1000")
For Each cell In rng
Filename = cell
If InStr(UCase(Filename), "JPG") > 0 Then
Worksheets("Import").Pictures.Insert(Filename).Select
Set theShape = Selection.ShapeRange.Item(1)
LinkToFile = msoFalse
SaveWithDocument = msoTrue
If theShape Is Nothing Then GoTo isnill
xCol = cell.Column
Set xRg = Cells(cell.Row, xCol)
With theShape
.LockAspectRatio = msoFalse
.ScaleHeight 0.13, msoFalse
.ScaleWidth 0.13, msoFalse
.Top = xRg.Top + (xRg.Height - .Height) / 2
.Left = xRg.Left + (xRg.Width - .Width) / 2
End With
isnill:
Set theShape = Nothing
Range("e1").Select
End If
Next
Application.ScreenUpdating = True
Debug.Print "Done " & Now
End Sub
I want to insert pictures in an Excel sheet next to its model name.
There is a loop to insert pictures row by row till last model.
The problem occurs when ppath is empty (blank http page). If empty the macro should go to Next.
On error resume next is crashing Excel. Error handler I tried is not working also (getting debug code on ppath).
How do I skip to Next when ppath is empty (no picture)?
Here is my code:
Sub insert_foto()
Dim i As Long
Dim ppath As String
Dim lastrow As Long
Dim ws As Worksheet
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Worksheets("sheet")
lastrow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
With ws
ws.Range("A6:A" & lastrow).RowHeight = 90
End With
'On Error Resume Next - is crashing excel when ppath is empty
On Error GoTo ErrHandler
For i = 6 To lastrow
' picture name in col A, ppath is where the pictures are
ppath = "http://aa/bb/" & CStr(Cells(i, 2).Value & "-F1.jpg")
'If ppath <> "" Then -tried this solution but not working
With ActiveSheet.Shapes.AddPicture(Filename:=ppath, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=50, Height:=85)
.Left = ActiveSheet.Cells(i, 1).Left + (ActiveSheet.Cells(i, 1).Width - .Width) / 2
.Top = ActiveSheet.Cells(i, 1).Top + (ActiveSheet.Cells(i, 1).Height - .Height) / 2
.Placement = 1
End With
' End If
ErrHandler:
'Resume Next
Next
Application.ScreenUpdating = True
End Sub
If AddPicture is asked to load an image that doesn't exist, it will throw an runtime error and of course not adding a new shape - that means it returns Nothing. To prevent the runtime error, you can insert a On Error Resume Next-statement, but please only for the one statement.
You mention that if you use On Error Resume Next, Excel crashes. With crashes, do you mean that Excel really crashes with an error message or that Excel seems to hang (no longer reacting)? If you try to access an image from the internet that doesn't exist, Excel needs to wait for a timeout and that can take some time (I had to wait for 60s for a server). If you do this multiple times, the execution may easily take a lot of time and during that, Excel will basically freeze. Adding a DoEvents will let Excel at least react after every download.
Have a look to the following code. It tries to load an image and save the result into a variable. If the loading fails, the variable will be Nothing and you know that the loading failed. As you are already using a worksheet variable, you should use that rather than ActiveSheet.
Dim sh As Shape
On Error Resume Next
Set sh = Nothing
Set sh = ws.Shapes.AddPicture(Filename:=pPath, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=50, Height:=85)
if sh is Nothing then
' Try an alternative image
Set sh = ws.Shapes.AddPicture(Filename:=pPath2, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=50, Height:=85)
End If
On Error GoTo 0
DoEvents
If sh Is Nothing Then
ws.Cells(i, 1) = "Image not found"
Else
With sh
.Left = ws.Cells(i, 1).Left + (ws.Cells(i, 1).Width - .Width) / 2
.Top = ws.Cells(i, 1).Top + (ws.Cells(i, 1).Height - .Height) / 2
.Placement = 1
End With
End If
sorry but the logic the answer gave isn't stopping the runtime error when ppath isn't found.
i had to implement the below. it uses an object from a reference pack in which you have to enable in your macro called Windows Script Host Object Model
Dim fso As New FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
Dim strFileName As String
strFileName = fso.GetFileName(ppath)
If strFileName Like "*jpg*" Then
' get images
Else
' do nothing
End If
I am working on automating an excel model by copying data from other sheets into a masterfile. I have a bit of an issue that after adding the code the file went from 25mb to 60mb, without changing the content, only adding the code. Below you can find a snippet of how I automated the imports
Sub copytest() 'Procedure for retrieving data from the sourcefiles
Dim wbTarget, wbSource As Workbook
Dim target As Object
Dim pathSource, fileName As String
Dim xlApp As Application
Dim lastRow As Long
Application.EnableEvents = False
Application.ScreenUpdating = False
'path where the data source folders are located (please keep all of them in the same directory)
pathSource = "C:\Users\vferraz\Desktop\crm stock\RAPOARTE IMPORTANTE\18.02\Rapoarte pentru Handsets\"
Set wbTarget = ThisWorkbook
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Application.CutCopyMode = False
'Stock 0001
Set wbSource = xlApp.Workbooks.Open(pathSource & "Stoc 0001.xls")
wbSource.Sheets(1).UsedRange.Copy
wbSource.Close
Set target = wbTarget.Sheets("Stock 0001")
target.UsedRange.Clear
Range("A1").Select
target.Paste
xlApp.Quit
Set wbSource = Nothing
Set xlApp = Nothing
ThisWorkbook.Sheets("Mastersheet").Activate
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
In the snippet above I only added the parsing of one file (Stock 0001), but the same method is done for other 10-15 files.
Does anyone have any ideas to improve the efficiency/size of this file based on this procedure?
P.S. Im aware that the "Paste" method might be adding formats rather than values only, then I tried adding .PasteSpecial xlPasteValues instead of paste but it eventually throw errors that I couldn't identify
Update:
Based on this solution, this is the new version I tried:
Stock 0001
Set wbSource = xlApp.Workbooks.Open(pathSource & "Stoc 0001.xls")
lastRow = wbSource.Sheets(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
wbTarget.Sheets("Stock 0001").Cells.Clear
wbSource.Sheets(1).Range("A1:C" & lastRow).Copy Destination:=wbTarget.Sheets("Stock 0001").Range("A1")
wbSource.Clo
The line wbSource.Sheets(1).Range("A1:C" & lastRow).Copy Destination:=wbTarget.Sheets("Stock 0001").Range("A1" Throws the "copy method of range class failed error.
Instead of this
'Stock 0001
Set wbSource = xlApp.Workbooks.Open(pathSource & "Stoc 0001.xls")
wbSource.Sheets(1).UsedRange.Copy
wbSource.Close
Set target = wbTarget.Sheets("Stock 0001")
target.UsedRange.Clear
Range("A1").Select
target.Paste
Try this
wbSource.Sheets(1).Columns("").Copy Destination:=wbTarget.Sheets("Stock 0001").Range("A1")
Where I've put Columns just replace this with whatever range you are using via Range() or Cells etc
Copy and Paste takes a while, and has issues if you are already copying something in another location. This just takes the data for you
Also, this piece of code will be your friend forever
With Sheets("Sheet1")
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
This finds the bottom row of Column A (or whatever your "always populated" column will be
Sub LastRow()
Dim wb As Workbook, ws As Worksheet, LastRow As Long
Set wb = ThisWorkbook
Set ws = Worksheets("Data")
LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
With ws.Range(ws.Cells(2, 13), ws.Cells(LastRow, 13))
'This is Range M2:M(bottom)
.
.
'etc
.
End With
End Sub
Edit....3:
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Application.CutCopyMode = False
'Stock 0001
Set wbSource = xlApp.Workbooks.Open(pathSource & "Stock 0001.xls")
Instead of all this, please use
Set wbSource = Workbooks.Open(pathSource & "Stock 0001.xls")
You also need error handling in your code. When it breaks (file doesn't exist, path is invalid, sheet doesn't exist) between
Application.EnableEvents = False
Application.ScreenUpdating = False
and
Application.EnableEvents = True
Application.ScreenUpdating = True
you're going to end up with Excel in a bad state where screen updating is off and events will no longer fire. What you should have is something long the lines of
On Error GoTo ExitErr
Application.EnableEvents = False
Application.ScreenUpdating = False
Then after your code, you should have
ExitErr:
Application.EnableEvents = True
Application.ScreenUpdating = True
I found a way to reduce the file size back to how it used to be by adding the following line to the imports after the paste command
target.Cells.ClearFormats
In this case the formats taken from the data were cleared.
Im using the below code to iterate over a table in excel that contains named ranges and position details for cells id like to copy over to a powerpoint presentation.
The code works perfectly. Except that, and for some reason its always random, the code throws a "Shapes.paste invalid request clipboard is empty" error. Debugging didnt help since it always stops at a different object or named range. I know VBA is a little finicky with its operations in that it starts the paste before actually completing the copy operation.
I tried the Application.Wait function which isnt the best solution, it slowed the code by 3 fold. As well do/doevents calls didnt help.
Any ideas on how to curb this VBA issue ??
Thanks!
Sub MyProcedure(PPT As Object, WKSHEET As String, RangeTitle As Range, SlideNumber As Long, FTsize As Variant, FT As Variant, SetLeft As Variant, SetTop As Variant, SetHeight As Variant, SetWidth As Variant, Bool As Boolean)
Dim shP As Object
Dim myShape As Object
Dim mySlide As Object
Dim tempSize As Integer, tempFont As String
Dim Mypath As String
Dim Myname As String
Dim myTitle As String
Dim ws As Worksheet
'Application.Calculation = xlManual
'Application.ScreenUpdating = False
Set ws = Worksheets(WKSHEET)
'select the name of report
Set shP = ws.Range(RangeTitle)
'select the ppt sheet you wish to copy the object to
Set mySlide = PPT.ActivePresentation.slides(SlideNumber)
'count the number of shapes currently on the PPT
shapeCount = mySlide.Shapes.Count
'copy the previously selected shape
Do
shP.Copy
'paste it on the PPT
DoEvents
mySlide.Shapes.Paste 'Special DataType:=ppPasteOLEObject, Link:=msoFalse
'wait until the count of shapes on the PPT increases, which signals that the past operation is finished.
'<~~ wait completion of paste operation
Loop Until mySlide.Shapes.Count > shapeCount
'adjust formatting of the newly copied shape: position on the sheet, font & size
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
With myShape
.Left = SetLeft
.Top = SetTop
.Width = SetWidth
.Height = SetHeight
.TextEffect.FontSize = FTsize
.TextEffect.FontName = FT
.TextEffect.FontBold = Bool
End With
'Application.CutCopyMode = False
'Application.Calculation = xlAutomatic
'Application.ScreenUpdating = True
End Sub
Sub LoopThrougMyData()
Dim FirstRow As Integer: FirstRow = 1
Dim LastRow As Integer: LastRow = Worksheets("Table").Range("A1").End(xlDown).Row
Dim iRow As Long
Dim PPT As Object
Set PPT = CreateObject("PowerPoint.Application")
Myname = ThisWorkbook.Name
Mypath = ThisWorkbook.Path
PPT.Visible = True
PPT.Presentations.Open Filename:=Mypath & "\Actuals Review Temp.pptx"
For iRow = FirstRow To LastRow 'loop through your table here
With Worksheets("Table").Range("test")
MyProcedure PPT, WKSHEET:=.Cells(iRow, "A"), RangeTitle:=.Cells(iRow, "B"), SlideNumber:=.Cells(iRow, "C"), FTsize:=.Cells(iRow, "D"), FT:=.Cells(iRow, "E"), SetLeft:=.Cells(iRow, "F"), SetTop:=.Cells(iRow, "G"), SetHeight:=.Cells(iRow, "H"), SetWidth:=.Cells(iRow, "I"), Bool:=.Cells(iRow, "J")
'call the procedure with the data from your table
End With
Next iRow
End Sub
It's more than likely a clipboard issue. This is a common bug in VBA when copying information from one application to the other application. The best solution I've found so far is simply pausing the Excel application for a few seconds in between the copy and paste. Now this won't fix the issue in every single instance but I would say 95% of the time it fixes the error. The other 5% of the time is simply the information being removed from the clipboard randomly.
Change this section:
shP.Copy
'paste it on the PPT
DoEvents
mySlide.Shapes.Paste 'Special DataType:=ppPasteOLEObject, Link:=msoFalse
With this:
'Copy the shape
shP.Copy
'Pause the Excel Application For Two Seconds
Application.Wait Now() + #12:00:02 AM#
'Paste the object on the slide as an OLEObject
mySlide.Shapes.Paste 'Special DataType:=ppPasteOLEObject, Link:=msoFalse
My issue is after I have imported a table from Microsoft Word into Excel by creating an OLEObject, it won't let me copy and paste the table into excel. It continually keeps pasting whatever was last copied on my clipboard into the first cell. Currently my code asks the user for the file name, opens that file as an OLEObject in the active excel sheet, and then pastes the incorrect information into cell A1. It's not copying and pasting what's inside the Word OLEObject.
Sub Macro1()
Dim FName As String, FD As FileDialog
Dim ExR As Range
Set FD = Application.FileDialog(msoFileDialogOpen)
FD.Show
If FD.SelectedItems.Count <> 0 Then
FName = FD.SelectedItems(1)
Else
Exit Sub
End If
ActiveSheet.OLEObjects.Add(fileName:=FName, Link:=False, DisplayAsIcon:=False).Select
Selection.Verb Verb:=xlPrimary
Range("A1").Select
ActiveSheet.Paste
End Sub
Thank you!
From Word to Excel, should be something like this.
Sub ImportFromWord()
'Activate Word Object Library
'Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("word.application") ' Open Word session
WordApp.Visible = False 'keep word invisible
Set WordDoc = WordApp.Documents.Open("C:\Users\your_path_here_\WordFile.docx") ' open Word file
'copy third row of first Word table
WordDoc.Tables(1).Rows(3).Range.Copy
'paste in Excel
Range("A1").PasteSpecial xlPasteValues
WordDoc.Close 'close Word doc
WordApp.Quit ' close Word
End Sub
Or this.
Sub GetTables()
FName = Application _
.GetOpenFilename("Word Files (*.doc), *.doc")
Set WordObject = GetObject(FName)
First = True
RowCount = 2
For Each Tble In WordObject.tables
For i = 1 To 22
If First = True Then
Data = Tble.Rows(i).Cells(1).Range
'Remove cell markers
Cells(1, i) = Left(Data, Len(Data) - 2)
End If
Data = Tble.Rows(i).Cells(2).Range.Text
'Remove cell markers
Cells(RowCount, i) = Left(Data, Len(Data) - 2)
Next i
RowCount = RowCount + 1
First = False
Next Tble
WordObject.Close savechanges = False
End Sub
Using the code from the link How to preserve source formatting while copying data from word table to excel sheet using VB macro? , I've only been able to get the code to work when the macro pastes my Word table in a whole new separate workbook. When clicking a command button that's within the excel workbook that I want to import the Word table to, the table never pastes into the sheet called "Scraping Sheets" I've messed around with the code, but the closest thing I could get was placing the entire table into one cell with all formatting lost.
Private Sub CommandButton22_Click()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim tbl As Object
FlName = Application.GetOpenFilename("Word files (*.Doc*),*.Doc*", , _
On Error Resume Next
Set oWordApp = GetObject(, "Word.Applicaton")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
Set tbl = oWordDoc.Tables(1)
Dim wb As Workbook, ws As Worksheet
Set wb = Workbooks.Open(""C:\Users\xxxx\Desktop\292 Int'l_Weekly_Win_Loss_YYYY MM DD TEMPLATE.xlsm"")
Set ws = wb.Sheets("Scraping Sheet")
tbl.Range.Copy
ws.Range("A1").Activate
ws.Paste
MsgBox "Successfully Added File!"
End Sub