Is it possible to display multiple images on 1 picturebox in running mode - vb6

When I try to google it for 3 days, I found that there is only 1 picture/image available in 1 picbox. My goal is to display multiple images, and they cannot overlap. If they overlap, there a red colour should be shown.
I'm using VB6. I'm using 1 combobox1, for select image n 1 commandbutoon. but when I select 2nd image in click button, the image on picbox will auto overwrite it. Is it caused by .cls ??
Private Sub Combo1_Click()
Dim pin As String
Dim intx As Integer
If UCase$(Combo1.List(intx)) = UCase$(pin) Then
Combo1.ListIndex = intx
End If
End Sub
Private Sub Command1_Click()
If Combo1.ListIndex = 0 Then
Set mPic = pin8.Image
ElseIf Combo1.ListIndex = 1 Then
Set mPic = pin12.Image
Else
Set mPic = pin16.Image
End If
mPicWidth = Me.ScaleX(mPic.Width, vbHimetric, Picture1.ScaleMode)
mPicHeight = Me.ScaleY(mPic.Height, vbHimetric, Picture1.ScaleMode)
ShowPictureAtPosition mLeft, mTop
End Sub
Thank you.
Best regard,
chan

Look, The only way to do that is to add 2 images as resources in the project then make one is the default picture or leave it blank as you wish.
The process now is when you click on the command button you switch between the two pictures.
Button Code:
if
PictureBox1.Image = My.Resources.<Name_of_res_file>.<Name_of_image1111_resource>
Then
PictureBox1.Image = My.Resources.<Name_of_res_file>.<Name_of_image2222_resource>
Else
PictureBox1.Image = My.Resources.<Name_of_res_file>.<Name_of_image1111_resource>
End If
This will switch between the 2 pictures. Hope this helps you.

Related

Excel UserForm button click slow response time when clicked fast

I have a VBA UserForm in Excel, with very simple code. It displays a collection (a dictionary, actually) of objects, one at a time, with buttons for "first, previous, next, and last". Everything works great, but if I were to continually click the next button to go through the items, I have to click it slowly (roughly once a second). If I click any faster, the click is ignored. For example, if I click four times over two seconds, it will only 'register' the first and third click and advance twice, instead of four times.
Below is example code for the 'next' button (and the other applicable pieces of code in the userform module):
Private dQIDs As Dictionary
Public Sub TransferQIDs(ByVal dIncomingQIDs As Dictionary)
Set dQIDs = dIncomingQIDs
End Sub
Private Sub bNext_Click()
Call LoadQID(CLng(lIndex.Caption) + 1)
End Sub
Private Sub LoadQID(lQID As Long)
Dim QID As cQID
Set QID = dQIDs(lQID)
lIndex.Caption = lQID
lItems.Caption = "Viewing new QID " & lQID & " of " & dQIDs.Count
Me.tQID = QID.lQID
Me.tTitle = QID.sTitle
Me.tVID = QID.sVendorID
Me.bOS = QID.bOSPatch
Me.bApp = Not QID.bOSPatch
Me.bPrev.Enabled = Not (lQID = 1)
Me.bFirst.Enabled = Not (lQID = 1)
Me.bNext.Enabled = Not (lQID = dQIDs.Count)
Me.bLast.Enabled = Not (lQID = dQIDs.Count)
End Sub
Any ideas?
Personally I would just disable to button while content is loaded.
Private Sub bNext_Click()
Dim b1 As Button
Set b1 = ActiveSheet.Buttons("LoadQID")
REM or Me.LoadQID
b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call LoadQID(CLng(lIndex.Caption) + 1)
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault
End Sub
Reason why this happens is that accessing a single object takes quite a bit of time in Excel. This way if you can click it will be registered.
Alternatively you can toggle UI update with:
Application.ScreenUpdating = False
Application.ScreenUpdating = True
windows is checking for a doubleclick. so if you click fast it registers a doubleclick.
2 options. increase you doubleclick speed in the windows mouse settings
or make a doubleclick event

Event Handlers for Dynamic Table Layout Panel in Visual Basic

I am making a risk-type game for school that dynamically creates a 4x4 grid of buttons inside a table layout panel in visual basic. I have successfully created the panel and buttons with names that correspond to the row and column of the button. There are also two parallel arrays - one for button owner and the other for button number - that correspond to the owner of the button and the number of "armies" in the button. My issue is that when the user clicks a certain button, I need to reference the button name/value to know how many "armies" the button has to control the "attack" portion of the player's turn.
The following code creates the table layout panel and the buttons with names.
'Create table Dynamically
Dim ColCount As Integer = 4
Dim RowCount As Integer = 4
Dim f As New System.Drawing.Font("Arial", 15)
riskTable.AutoScroll = True
riskTable.Dock = DockStyle.Fill
riskTable.ColumnCount = ColCount
riskTable.RowCount = RowCount
For rowNo As Integer = 0 To riskTable.RowCount - 1
For columnNo As Integer = 0 To riskTable.ColumnCount - 1
Dim buttonname As String
buttonname = "B" & rowNo & columnNo
Dim button As Control = New Button
button.Size = New Size(179, 100)
button.Name = buttonname
button.Text = "1"
button.ForeColor = Color.White
button.Font = f
AddHandler button.Click, AddressOf buttonname_Click
riskTable.Controls.Add(button, columnNo, rowNo)
Next
Next
Me.Controls.Add(riskTable)
This is the dynamic event handler that I created. I tried using 'Me.Click' to get the name of the button, but it only returns the name of the form. I need to have code in here that references the name of the currently clicked button to then in turn reference the box owner and box number arrays.
Private Sub buttonname_Click(sender As Object, e As EventArgs) Handles Me.Click
MessageBox.Show(Me.Name)
End Sub
Any help would be greatly appreciated! I think that once I get this working, the rest of the game will be pretty simple to figure out.
Thanks!
Put the name in 'button.Tag' instead/also:
button.Tag = buttonname
Then it is easy to get the name with:
Private Sub buttonname_Click(sender As Object, e As EventArgs) Handles Me.Click
Dim result As String = CType(CType(sender, System.Windows.Forms.Button).Tag, String)
End Sub
(Check the System.Windows.Forms.Button though, might need some tweak to match your buttons inside the table. riskTable.Controls.button ?)

Export Pictures Excel VBA

I'm having trouble trying to select and export all pictures from a workbook. I only want the pictures. I need to select and save all of them as:"Photo 1", "Photo 2", "photo 3", and so on, in the same folder of the workbook.
I have already tried this code:
Sub ExportPictures()
Dim n As Long, shCount As Long
shCount = ActiveSheet.Shapes.Count
If Not shCount > 1 Then Exit Sub
For n = 1 To shCount - 1
With ActiveSheet.Shapes(n)
If InStr(.Name, "Picture") > 0 Then
Call ActiveSheet.Shapes(n).CopyPicture(xlScreen, xlPicture)
Call SavePicture(ActiveSheet.Shapes(n), "C:\Users\DYNASTEST-01\Desktop\TEST.jpg")
End If
End With
Next
End Sub
This code is based on what I found here. It has been heavily modified and somewhat streamlined. This code will save all the pictures in a Workbook from all Worksheets to the same folder as the Workbook, in JPG format.
It uses the Export() Method of the Chart object to accomplish this.
Sub ExportAllPictures()
Dim MyChart As Chart
Dim n As Long, shCount As Long
Dim Sht As Worksheet
Dim pictureNumber As Integer
Application.ScreenUpdating = False
pictureNumber = 1
For Each Sht In ActiveWorkbook.Sheets
shCount = Sht.Shapes.Count
If Not shCount > 0 Then Exit Sub
For n = 1 To shCount
If InStr(Sht.Shapes(n).Name, "Picture") > 0 Then
'create chart as a canvas for saving this picture
Set MyChart = Charts.Add
MyChart.Name = "TemporaryPictureChart"
'move chart to the sheet where the picture is
Set MyChart = MyChart.Location(Where:=xlLocationAsObject, Name:=Sht.Name)
'resize chart to picture size
MyChart.ChartArea.Width = Sht.Shapes(n).Width
MyChart.ChartArea.Height = Sht.Shapes(n).Height
MyChart.Parent.Border.LineStyle = 0 'remove shape container border
'copy picture
Sht.Shapes(n).Copy
'paste picture into chart
MyChart.ChartArea.Select
MyChart.Paste
'save chart as jpg
MyChart.Export Filename:=Sht.Parent.Path & "\Picture-" & pictureNumber & ".jpg", FilterName:="jpg"
pictureNumber = pictureNumber + 1
'delete chart
Sht.Cells(1, 1).Activate
Sht.ChartObjects(Sht.ChartObjects.Count).Delete
End If
Next
Next Sht
Application.ScreenUpdating = True
End Sub
One easy approach if your excel file is an Open XML format:
add a ZIP extension to your filename
explore the resulting ZIP package, and look for the \xl\media subfolder
all your embedded pictures should be located there as independent image files
Ross's method works well but using the add method with Chart forces to leave the currently activated worksheet... which you may not want to do.
In order to avoid that you could use ChartObject
Public Sub AddChartObjects()
Dim chtObj As ChartObject
With ThisWorkbook.Worksheets("A")
.Activate
Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
chtObj.Name = "TemporaryPictureChart"
'resize chart to picture size
chtObj.Width = .Shapes("TestPicture").Width
chtObj.Height = .Shapes("TestPicture").Height
ActiveSheet.Shapes.Range(Array("TestPicture")).Select
Selection.Copy
ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
ActiveChart.Paste
ActiveChart.Export Filename:="C:\TestPicture.jpg", FilterName:="jpg"
chtObj.Delete
End With
End Sub

Using VBA to change Picture

I am trying to use VBA to automate the Change Picture function when you right click a Shape in Excel/Word/Powerpoint.
However, I am not able to find any reference, can you assist?
So far as I know you can't change the source of a picture, you need to delete the old one and insert a new one
Here's a start
strPic ="Picture Name"
Set shp = ws.Shapes(strPic)
'Capture properties of exisitng picture such as location and size
With shp
t = .Top
l = .Left
h = .Height
w = .Width
End With
ws.Shapes(strPic).Delete
Set shp = ws.Shapes.AddPicture("Y:\our\Picture\Path\And\File.Name", msoFalse, msoTrue, l, t, w, h)
shp.Name = strPic
shp.ScaleHeight Factor:=1, RelativeToOriginalSize:=msoTrue
shp.ScaleWidth Factor:=1, RelativeToOriginalSize:=msoTrue
You can change the source of a picture using the UserPicture method as applied to a rectangle shape. However, you will need to resize the rectangle accordingly if you wish to maintain the picture's original aspect ratio, as the picture will take the dimensions of the rectangle.
As an example:
ActivePresentation.Slides(2).Shapes(shapeId).Fill.UserPicture ("C:\image.png")
'change picture without change image size
Sub change_picture()
strPic = "Picture 1"
Set shp = Worksheets(1).Shapes(strPic)
'Capture properties of exisitng picture such as location and size
With shp
t = .Top
l = .Left
h = .Height
w = .Width
End With
Worksheets(1).Shapes(strPic).Delete
Set shp = Worksheets(1).Shapes.AddPicture("d:\pic\1.png", msoFalse, msoTrue, l, t, w, h)
shp.Name = strPic
End Sub
what I do is lay both images on top of eachother, and assign the macro below to both images. Obviously i've named the images "lighton" and "lightoff", so make sure you change that to your images.
Sub lightonoff()
If ActiveSheet.Shapes.Range(Array("lighton")).Visible = False Then
ActiveSheet.Shapes.Range(Array("lighton")).Visible = True
Else
ActiveSheet.Shapes.Range(Array("lighton")).Visible = False
End If
End Sub
What I've done in the past is create several image controls on the form and lay them on top of each other. Then you programmatically set all images .visible = false except the one you want to show.
In Word 2010 VBA it helps to change the .visible option for that picture element you want to change.
set the .visible to false
change the picture
set the .visilbe to true
that worked for me.
I tried to imitate the original function of 'Change Picture' with VBA in PowerPoinT(PPT)
The code below tries to recover following properties of the original picture:
- .Left, .Top, .Width, .Height
- zOrder
- Shape Name
- HyperLink/ Action Settings
- Animation Effects
Option Explicit
Sub ChangePicture()
Dim sld As Slide
Dim pic As Shape, shp As Shape
Dim x As Single, y As Single, w As Single, h As Single
Dim PrevName As String
Dim z As Long
Dim actions As ActionSettings
Dim HasAnim As Boolean
Dim PictureFile As String
Dim i As Long
On Error GoTo ErrExit:
If ActiveWindow.Selection.Type <> ppSelectionShapes Then MsgBox "Select a picture first": Exit Sub
Set pic = ActiveWindow.Selection.ShapeRange(1)
On Error GoTo 0
'Open FileDialog
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Picture File", "*.emf;*.jpg;*.png;*.gif;*.bmp"
.InitialFileName = ActivePresentation.Path & "\"
If .Show Then PictureFile = .SelectedItems(1) Else Exit Sub
End With
'save some properties of the original picture
x = pic.Left
y = pic.Top
w = pic.Width
h = pic.Height
PrevName = pic.Name
z = pic.ZOrderPosition
Set actions = pic.ActionSettings 'Hyperlink and action settings
Set sld = pic.Parent
If Not sld.TimeLine.MainSequence.FindFirstAnimationFor(pic) Is Nothing Then
pic.PickupAnimation 'animation effect <- only supported in ver 2010 above
HasAnim = True
End If
'insert new picture on the slide
Set shp = sld.Shapes.AddPicture(PictureFile, False, True, x, y)
'recover original property
With shp
.Name = "Copied_ " & PrevName
.LockAspectRatio = False
.Width = w
.Height = h
If HasAnim Then .ApplyAnimation 'recover animation effects
'recover shape order
.ZOrder msoSendToBack
While .ZOrderPosition < z
.ZOrder msoBringForward
Wend
'recover actions
For i = 1 To actions.Count
.ActionSettings(i).action = actions(i).action
.ActionSettings(i).Run = actions(i).Run
.ActionSettings(i).Hyperlink.Address = actions(i).Hyperlink.Address
.ActionSettings(i).Hyperlink.SubAddress = actions(i).Hyperlink.SubAddress
Next i
End With
'delete the old one
pic.Delete
shp.Name = Mid(shp.Name, 8) 'recover name
ErrExit:
Set shp = Nothing
Set pic = Nothing
Set sld = Nothing
End Sub
How to use:
I suggest you to add this macro into the Quick Access Toolbar list.
(Goto Option or Right-click on the Ribbon menu))
First, select a Picture on the slide which you want to change.
Then, if the FileDialog window opens, choose a new picture.
It's done. By using this method, you can bypass the 'Bing Search and One-Drive Window' in ver 2016 when you want to change a picture.
In the code, there might(or should) be some mistakes or something missing.
I'd appreciate it if somebody or any moderator correct those errors in the code.
But mostly, I found that it works fine.
Also, I admit that there are still more properties of the original shape to recover - like the line property of the shape, transparency, pictureformat and so on.
I think this can be a beginning for people who want to duplicate those TOO MANY properties of a shape.
I hope this is helpful to somebody.
i use this code :
Sub changePic(oshp As shape)
Dim osld As Slide
Set osld = oshp.Parent
osld.Shapes("ltkGambar").Fill.UserPicture (ActivePresentation.Path & "\" & oshp.Name & ".png")
End Sub
I'm working in Excel and VBA. I can't overlay images because I have multiple sheets of a variable number and each sheet has the images, so the file would get huge if, say 20 sheets had all 5 images I want to animate.
So I used a combination of these tricks listed here:
1) I inserted an RECTANGLE shape at the location and size I wanted:
ActiveSheet.Shapes.AddShape(msoShapeRectangle, 1024#, 512#, 186#, 130#).Select
Selection.Name = "SCOTS_WIZARD"
With Selection.ShapeRange.Fill
.Visible = msoTrue
.UserPicture "G:\Users\ScotLouis\Documents\My Spreadsheets\WordFind Wizard\WordFind Wizard 1.jpg"
.TextureTile = msoFalse
End With
2) Now to animate (change) the picture, I only need to change the Shape.Fill.UserPicture:
ActiveSheet.Shapes("SCOTS_WIZARD").Fill.UserPicture _
"G:\Users\ScotLouis\Documents\My Spreadsheets\WordFind Wizard\WordFind Wizard 2.jpg"
So I've accomplished my goal of only having 1 picture per sheet (not 5 as in my animation) and duplicating the sheet only duplicates the active picture, so the animation continues seamlessly with the next picture.
![Please find attached code.
First create a shape in PPT and run the code]1

Is there an Alternative to using the LoadPicture("bmp_or_icon_file_path") to loading Images in Excel 2007 VBA

I have an Excel 2007 Worksheet with many buttons and labels that act as menu options (i.e. user clicks the buttons, labels with images) and is presented with forms, or some thing else.
These images / icons for the buttons and labels are loaded in VBA by assigning the Picture property of the Control and calling LoadPicture() method with the full image file path as parameter, like So.
With SomeFormObject
.cmdOpenFile.Picture = LoadPicture("F:\projectname\images\fileopen.BMP")
End With
This method of loading images for buttons, other controls is causing 2 issues.
1) It creates a dependency on the image files and physical location for every user, so if a user does not have the drive mapped and files present, the VBA fails with runtime error of file or path not found.
2)
The app gets very slow if the images are on a shared drive (which is the case)
I want to eliminate both issues and somehow load icons, images into control internally, without any external dependencies on external image files.
What is the best way to achieve this in Excel 2007 VBA?
I could not file any Visual Basic 6.0 / Visual Studio style "Resource File Editor" / feature with which to accomplish this.
Please advice! thank you
-Shiva #
mycodetrip.com
I really hope that there is a easier way to do this, but this is the only one I found:
The Idea is:
You keep the Pictures embedded in a Sheet and every time you want to set the pictures for the Command you export them from your worksheet to a file and load them through LoadPicture. The only way to export an embedded Picture through VBA that I found is by making it a Chart first.
The following code is based on 'Export pictures from Excel' from johnske
Option Explicit
Sub setAllPictures()
setPicture "Picture 18", "CommandButtonOpen"
setPicture "Picture 3", "CommandButtonClose"
End Sub
Sub setPicture(pictureName As String, commandName As String)
Dim pictureSheet As Worksheet
Dim targetSheet As Worksheet
Dim embeddedPicture As Picture
Dim pictureChart As Chart
Dim MyPicture As String
Dim PicWidth As Long
Dim PicHeight As Long
Set pictureSheet = Sheets("NameOfYourPictureSheet") ' <- to Change '
Set targetSheet = Sheets("NameOfYourSheet") ' <- to Change '
Set embeddedPicture = pictureSheet.Shapes(pictureName).OLEFormat.Object
With embeddedPicture
MyPicture = .Name
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=pictureSheet.Name
Set pictureChart = ActiveChart
embeddedPicture.Border.LineStyle = 0
With pictureChart.Parent
.Width = PicWidth
.Height = PicHeight
End With
With pictureSheet
.Select
.Shapes(MyPicture).Copy
With pictureChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="temp.jpg", FilterName:="jpg"
End With
pictureChart.Parent.Delete
Application.ScreenUpdating = True
targetSheet.Shapes(commandName).OLEFormat.Object.Object.Picture = LoadPicture("temp.jpg")
Set pictureChart = Nothing
Set embeddedPicture = Nothing
Set targetSheet = Nothing
Set pictureSheet = Nothing
End Sub
Sub listPictures()
' Helper Function to get the Names of the Picture-Shapes '
Dim pictureSheet As Worksheet
Dim sheetShape As Shape
Set pictureSheet = Sheets("NameOfYourSheet")
For Each sheetShape In pictureSheet.Shapes
If Left(sheetShape.Name, 7) = "Picture" Then Debug.Print sheetShape.Name
Next sheetShape
Set sheetShape = Nothing
Set pictureSheet = Nothing
End Sub
To Conclude:
Loading the Images from a Mapped Networked Drive seems less messy, and there shouldn't be that much of a speed difference.
2 alternatives i can think of: form.img.picture=pastepicture , and = oleobjects("ActiveXPictureName").object.picture.

Resources