I'm trying to write a script that will allow me to load pictures contained in my workbook into my userform dynamically in an attempt to make the workbook completely portable. I've come up with the following that seems to work but there is one line which I don't understand why it doesn't work without. If I remove the line .ChartArea.Select the image won't load. However, If I leave it in it works fine. Ideally I'd like to remove it so I can avoid using a pointless Select. Can anyone explain?
Option Explicit
Private Sub UserForm_Initialize()
Me.Picture = LoadPicture(Filename:=ExportMyPicture(Sheet1.Pictures(1)))
Me.PictureSizeMode = fmPictureSizeModeZoom
End Sub
Private Function ExportMyPicture(pic As Picture) As String
Dim fName As String
fName = Environ("Temp") & "/" & pic.Name & ".bmp"
With pic.Parent.ChartObjects.Add(50, 40, pic.ShapeRange.Width, pic.ShapeRange.Height)
.Border.LineStyle = 0
pic.Copy
With .Chart
' Removing the following line stops the picture from loading
.ChartArea.Select
.Paste
If .Export(Filename:=fName, filtername:="bmp") Then
ExportMyPicture = fName
End If
End With
.Delete
End With
End Function
Demo:
Using this png:
url: SO converts it to a jpg
http://pngimg.com/uploads/cat/cat_PNG50497.png
Picture by Mikku
It has all looks of a timing issue, which could be a bug in how the OLE object is implementing its .Copy method; the .Select call gives it the kick it needs to get back on track.
Comments are there to say why we do things. This is one of these cases where commenting is simply the best possible thing to do... your comment isn't bad at all - it explains why, not what - and that is exactly what we want comments to say.
' Removing the following line stops the picture from loading
.ChartArea.Select
Some alternatives:
.ChartArea.Select ' Picture.Copy timing issue; this prevents subsequent .Paste from being no-op.
.ChartArea.Select ' HERE BE DRAGONS! Remove this instruction and you'll break the .Paste!
It looks like it may be a timing issue. If you pause the macro for a few seconds after copying the picture to the clipboard, it creates a file with the image and loads it successfully. However, .ChartArea.Select seems to be a good workaround. In any case, if you want to try pausing the macro, here's an example...
Option Explicit
Private Sub UserForm_Initialize()
Me.Picture = LoadPicture(Filename:=ExportMyPicture(Sheet1.Pictures(1)))
Me.PictureSizeMode = fmPictureSizeModeZoom
End Sub
Private Function ExportMyPicture(pic As Picture) As String
Dim fName As String
fName = Environ("Temp") & "/" & pic.Name & ".bmp"
With pic.Parent.ChartObjects.Add(50, 40, pic.ShapeRange.Width, pic.ShapeRange.Height)
.Border.LineStyle = 0
pic.Copy
PauseMacro
With .Chart
.Paste
If .Export(Filename:=fName, filtername:="bmp") Then
ExportMyPicture = fName
End If
End With
.Delete
End With
End Function
Private Sub PauseMacro()
Dim StartTime As Single
StartTime = Timer
Do Until Timer > StartTime + 3 'seconds delay
DoEvents
Loop
End Sub
Note that a 1 second delay seems to work as well, but maybe best to keep it at a 3 second delay just in case.
Related
First of all I'm not very good at Excel macro.
After going through multiple forums, I managed to come up with a code to Crop images in a folder using Excel VBA.
the code opens up each image in Excel, paste in a chart, crop the image, resize to match the height & width and then replace the original image with the edited image.
Macro is working fine with F8 but when I run the macro fully, Images are not getting replaced with the edited one, instead it's replacing with blank image.
After digging through multiple options, the only conclusion I came up with is the macro is running fine in Excel 2013 but it's not running properly with office 365.
Can anybody help me, how to resolve this or have any better code to run?
Option Explicit
Sub ImportData()
Dim XL As Object
Dim thisPath As String
Dim BooksPAth As String
BooksPAth = "C:\Images\"
thisPath = ActivePresentation.path
Set XL = CreateObject("Excel.Application")
Run "Crop_vis", BooksPAth
End Sub
Sub DeleteAllShapes()
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
If Not (Shp.Type = msoOLEControlObject Or Shp.Type = msoFormControl) Then Shp.Delete
Next Shp
End Sub
Sub Crop_Vis(ByVal folderPath As String)
Dim Shp As Object, path As String, sht As Worksheet, s As Shape, TempChart As String
'Dim folderPath As String
Application.ScreenUpdating = True
If folderPath = "" Then Exit Sub
Set sht = Sheet1
sht.Activate
sht.Range("A10").Activate
path = Dir(folderPath & "\*.jpg")
Do While path <> ""
DeleteAllShapes
Set Shp = sht.Pictures.Insert(folderPath & "\" & path)
' Use picture's height and width.
Set s = sht.Shapes(sht.Shapes.Count)
s.PictureFormat.CropTop = 50
s.Width = 768
s.Height = 720
'Add a temporary chart in sheet1
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=sht.Name
Selection.Border.LineStyle = 0
TempChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)
With sht
'Change the dimensions of the chart to suit your need
With .Shapes(TempChart)
.Width = s.Width
.Height = s.Height
End With
'Copy the picture
s.Copy
'Paste the picture in the chart
With ActiveChart
.ChartArea.Select
.Paste
End With
'Finally export the chart
.ChartObjects(1).Chart.Export fileName:=folderPath & "\" & path, FilterName:="jpg"
'Destroy the chart. You may want to delete it...
.Shapes(TempChart).Cut
End With
path = Dir
Loop
DeleteAllShapes
Application.DisplayAlerts = False
End Sub
Before
'Finally export the chart
insert something like this, to make sure that pasting of the image into the chart has finished:
Do
If ActiveChart.Shapes.Count > 0 Then
Exit Do
End If
Loop
The problem is with the pasting. When you tell it to paste the clipboard (image) into the chart, sometimes it ignores you. When you go to export the chart, you end up with an empty image.
It's not that you have to wait for it to paste, because it's not going to - it ignored you. I have no idea why it ignores you, or why it doesn't error out when it ignores you - it just ignores you with no warning. Maybe Windows is just too busy under the hood to paste.
Basically, what you have to do is check to see if it pasted, and if not, paste again....and again....until it finally sees fit to process your instruction.
I debugged, Googled, trialed and errored and banged my head on the wall for week on this and finally ended up with this:
Sub SavePictureFromExcel(shp As Shape, SavePath As String)
Dim Imagews As Worksheet
Dim tempChartObj As ChartObject
Dim ImageFullPath As String
Set Imagews = Sheets("Image Files")
Set tempChartObj = Imagews.ChartObjects.Add(0, 0, shp.Width, shp.Height)
shp.Copy
tempChartObj.Chart.ChartArea.Format.Line.Visible = msoFalse 'No Outline
tempChartObj.Chart.ChartArea.Format.Fill.Visible = msoFalse 'No Background
Do
DoEvents
tempChartObj.Chart.Paste
Loop While tempChartObj.Chart.Shapes.Count < 1
ImageFullPath = SavePath & "\" & shp.Name & ".png"
tempChartObj.Chart.Export ImageFullPath, Filtername:="png"
tempChartObj.Delete
End Sub
I want to copy a variable to the clipboard using the PutInClipboard-methode. Due to a known bug in Win10 I need to verify if the content of the clipboard is actually what it's suppose to be.
Unfortunalty it does not work as expected and I need to "enforce" the PutInClipboard-methode by using the wait-Methode, otherwise the comparison returns true, even though the values should not be the same:
'Put the content of a variable into the clipbaord
Dim strDesiredClipboardContent as String
Dim dataObject1 As DataObject
Set dataObject1 = New DataObject
dataObject1.SetText strDesiredClipboardContent
dataObject1.PutInClipboard
'Enforce Execution (otherwise the comparison in the end does not work)
Application.Wait Now + #12:00:01 AM#
'Get whatever is in the clipboard
Dim strActuallClipboardContent
Dim dataObject2 As MSForms.DataObject
Set dataObject2 = New MSForms.DataObject
dataObject2.GetFromClipboard
strActuallClipboardContent = dataObject2.GetText
'Compare
If strDesiredClipboardContent <> strActuallClipboardContent Then
MsgBox "Error"
End If
End Sub
I wonder if there is a different methode to enforce the complete execution of the PutInClipboard-methode then using wait()?! The goal would be to get the correct results but to ad as little "wait-time" as possible.
You could also seperate your macro into 2 parts (e.g.: Macro1 and Macro2) and at the end of the first macro you would use
Application.Ontime Now + TimeSerial(0, 0, 1), "Macro2"
to execute the second part of your code after waiting 1 second.
In my experience, this is more reliable than using Wait or even DoEvents since this will make sure the VBA process completely ends for a brief second. From what I understand, this leaves priority to Excel and the OS to complete the operations that needs to be done i.e.: put string content in the clipboard.
I wrote some code to look for external links to "file A" and replace them with links to "file B". The code is in PowerPoint, "file A" and "file B" are both excel files. The PowerPoint file has about 25 "objects" linked to excel (the objects are primarily just cells from excel pasted into PowerPoint as linked objects).
The code works, but it takes 7-8 minutes to run. Any idea why it takes so long or how to make it faster? It seems as all it's doing is finding and replacing text, so I'm confused as to why it takes so much time.
Relevant portion of code:
Dim newPath As String
Dim templateHome As String
Dim oshp As Shape
Dim osld As Slide
Dim vizFile As Workbook
Dim vizFname As String
Dim replacethis As String
Dim replacewith As String
'3. Update links:
'(Replace links to template file link with links to new copy of the file)
replacethis = templateHome & vizFname
replacewith = newPath & "\" & vizFname
On Error Resume Next
For Each osld In ActivePresentation.Slides
For Each oshp In osld.Shapes
oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
oshp.LinkFormat.Update
Next oshp
Next osld
This code is pretty clean, so there's probably not a lot you can do to optimize it, but I would caution you that it's doing more than just "finding and replacing text" :) Each call to UpdateLink retrieves data from some external source. That's not just simple string replacement!
Firstly: On Error Resume Next is swallowing a lot of errors (i.e., any shape that isn't a linked object, so, most of them), that's potentially increasing your runtime and might be better if you code around those errors rather than just eating them with Resume Next.
' On Error Resume Next ' ## Comment or remove this line :)
For Each osld In ActivePresentation.Slides
For Each oshp In osld.Shapes
If oshp.Type = msoLinkedOLEObject Then
oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
oshp.LinkFormat.Update
End If
Next
Next
Also, you're calling on the oshp.LinkFormat.Update repeatedly. It is probably better to do all your text replacing in the loop, but instead of updating individual links, update them all at once outside of the loop using the Presentation.UpdateLinks method:
' On Error Resume Next ' ## Comment or remove this line :)
For Each osld In ActivePresentation.Slides
For Each oshp In osld.Shapes
If oshp.Type = msoLinkedOLEObject Then
oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
' ## REMOVE oshp.LinkFormat.Update
End If
Next
Next
' Now, update the entire presentation:
ActivePresentation.UpdateLinks
I have a form that manipulates a chart and then exports it, like so:
Workbooks(sWB).Sheets("Output").Unprotect sPW
Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName
However, occasionally this doesn't work properly anymore and a corrupt image is exported each time. Going to the sheet with the chart and scrolling over it (without clicking) solves the issue for a while. For now I fixed it like this:
Workbooks(sWB).Sheets("Output").Unprotect sPW
Workbooks(sWB).Sheets("Output").ChartObjects(1).Activate 'chart sometimes falls asleep somehow, maybe this will fix
Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName
This seems to have solved the issue which I dubbed "sleeping charts" for now.
However, I would like to understand how this works, and to fix it without using "Activate" as that can impact the user experience of my users (who use multiple Excel sheets along this VBA-excel form).
Anyone who understands what happens here?
Full function code chain
Private Sub C171CmdLe1Dr1Graph_Click()
Call ShowGraph(1, 1, True)
End Sub
Private Sub ShowGraph(ByVal intLeNr As Integer, ByVal intDrNr As Integer, ByVal Show As Boolean) 'Delete
Dim strDocName As String
Dim strLeNr As String
Dim oChart As Frm_DCT_ShowGraph
Call dle(intLeNr - 1).DrawChart(intLeNr, intDrNr)
'export the chart
strDocName = strMyDocsPath & "\DRT_Chart" & Right(strLeNr, 1) & ".gif"
Workbooks(sWB).Sheets("Output").Unprotect sPW
Workbooks(sWB).Sheets("Output").ChartObjects(1).Activate 'chart sometimes falls asleep somehow, maybe this will fix
Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName
If Show Then
'create new chart, load it and show it
Set oChart = New Frm_DCT_ShowGraph
oChart.DocName = strDocName
oChart.Show vbModeless
End If
Workbooks(sWB).Sheets("Output").Protect sPW
DoEvents
End Sub
Public Sub DrawChart(ByVal intLeNr As Integer, ByVal intDrNr As Integer)
Dim lngN As Long
Dim sngPlotArr() As Single
Dim strIRange As String
Dim strURange As String
...
'create plot data
Call cDriver(intDrNr - 1).Plot(sngPlotArr)
'unlock worksheet
Workbooks(sWB).Sheets("Output").Unprotect sPW
'clear range first
Workbooks(sWB).Sheets("Output").Range(strIRange).Clear
Workbooks(sWB).Sheets("Output").Range(strURange).Clear
'fill in data
For lngN = 0 To UBound(sngPlotArr, 1)
Workbooks(sWB).Sheets("Output").Range(strIRange).Columns(lngN + 1).Value2 = sngPlotArr(lngN, 0)
Workbooks(sWB).Sheets("Output").Range(strURange).Columns(lngN + 1).Value2 = sngPlotArr(lngN, 1)
'give OS some time
If lngN Mod 100 = 0 Then
DoEvents
End If
Next
...
'relock
Workbooks(sWB).Sheets("Output").Protect sPW
End Sub
I've written some VBA script to load a webpage then copy the entire html contents into a string, then select specific data from that string. In essence I search for a rail timetable, then copy out details for 5 journeys (departure time, interchanges, journey time & cost)
I have the above script sorted to do one search, but I now want to loop it and run approximately 300 searches. The issue I've found is that the script won't wait for the webpage to open, and therefore the string returned is empty, effectively returning nothing.
What I need to do is load an address, wait for the page to load, then continue the script. Do you have any suggestions? I've searched a lot and just haven't been able to sort, I've tried Application.Wait in a number of places and still no further ahead.
The code I'm using is below:
Sub CreateIE()
Dim tOLEobject As OLEobject
Dim NRADDRESS As String
NRADDRESS = Range("h11")
On Error Resume Next
Worksheets("Sheet1").Shapes.Range(Array("WebBrow")).Delete
Set tOLEobject = Worksheets("Sheet1").OLEObjects.Add(ClassType:="Shell.Explorer.2",Link:=False, _
DisplayAsIcon:=False, Left:=0, Top:=15, Width:=912, Height:=345)
For Each tOLEobject In Worksheets("Sheet1").OLEObjects
If tOLEobject.Name = "WebBrowser1" Then
With tOLEobject
.Left = 570
.Top = 1
.Width = 510
.Height = 400
.Name = "WebBrow"
End With
With tOLEobject.Object
.Silent = True
.MenuBar = False
.AddressBar = False
.Navigate NRADDRESS
End With
End If
Next tOLEobject
Sheets("Sheet2").Activate
Sheets("Sheet1").Activate
Call ReturnText
End Sub
NRADDRESS is a web address made up of a number of different parameters (origin, destination, date and time)
The "Call ReturnText" is the script I use to copy the website HTML into a string and extract what I want.
In that case, you might try something like this:
Set objIE = CreateObject("InternetExplorer.Application")
objIE.navigate strURL
Do While objIE.readyState <> 4 And objIE.Busy
DoEvents
Loop
which, I believe, requires a reference to Microsoft Internet Controls.
When I first started using VBA to load webpages, I also used the IE Object, but later found it creates all kinds of complications I didn't need, when all I really wanted was to download the file. Now I always use URLDownloadToFile.
A good example of it's use can be found here:
VBA - URLDownloadToFile - Data missing in downloaded file