I want to use vba (macro) to insert a photo into a cell on the MacBook, but it is used well in Windows Excel, but it is not used in the MacBook. Is it because the path to load the photo file is different? Can I modify this vba to be usable on macbook?
I'm getting an execution error in the bolded part of the code below.
Sub insert_Pic()
Dim Pic As Variant
***Pic = Application.GetOpenFilename(filefilter:="Picture Files,*.jpg;*.bmp;*.tif;*.gif;*.png")***
If Pic = False Then Exit Sub
With ActiveSheet.Pictures.Insert(Pic).ShapeRange
.LockAspectRatio = msoFalse
.Height = Selection.Height - 4
.Width = Selection.Width - 4
.Left = Selection.Left + 2
.Top = Selection.Top + 2
End With
End Sub
I have a form that sets up a list of labels with content and an accompanying checkbox on initialisation.
I want to check the value of a checkbox when a button is clicked.
How do I reference back to the checkbox - I have called the checkbox a number (the value of i) when they are created.
Code to add the checkbox:
Sub addLabel()
Dim theCheck As Object
Dim theLabel As Object
Dim i As Long
Dim LastRow As Integer
LastRow = Worksheets("Assumptions").Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To LastRow
Set theLabel = UserForm1.Controls.Add("Forms.Label.1", "Assumption" & i, True)
With theLabel
.Name = "Assumption" & i
.Caption = Worksheets("Assumptions").Range("B" & i).Value ' & labelCounter
.Left = 156
.Width = 500
.Top = 138 + i * 20
End With
Set theCheck = UserForm1.Controls.Add("Forms.CheckBox.1", i, True)
With theCheck
.Name = i
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
Next
End Sub
My ultimate goal is to check which checkbox is 'True' and then IF true enter the accompanying label content into a worksheet.
My main struggle at the moment is how to reference the checkboxes by name (e.g. loop through them all where they are called 1-10 for example.
Thanks
To make reference of an object in your form you can use the following syntax
<Name of your form>.<Name of your control>
In you can I believe that something like UserForm1.1 but this is not a great idea to call your checkbox only with a number, give it with a proper name.
I strongly recommend that you change
With theCheck
.Name = i 'This is not great
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
By something more explicit like
With theCheck
.Name = "cb" & i 'Not great but better
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
Loop through each Checkbox in your form
To go through each Checkbox and check if it's checked or not, you can use something like this
'Go through each control in your UserForm
For Each myControl In UserForm1.Controls
'If the current control is a Checkbox
If (TypeName(myControl) = "Checkbox") Then
'Check it's value
If (myControl.Value = True) Then
'Do whatever you want
'You can access your checkbox properties with myControl.YOUR_PROPERTY
End If
End If
Next myControl
I have problem resizing plot area in an embedded chart in excel
Dim myChart As Chart
maxPie = ThisWorkbook.Sheets(sheetName).Range("A1048576").End(xlUp).Row
Set myChart = ThisWorkbook.Sheets(sheetName).Shapes.AddChart.Chart
myChart.ChartType = xlBarClustered
myChart.SetSourceData Source:=Range(sheetName & "!$A$5:$C$" & maxPie)
With myChart.Parent
.Top = 10
.Left = 500
.Width = 500
.Height = 500
End With
With myChart.PlotArea
.Top = 70
.Height = 420
End With
if i press debug and then F5 then it resizes it, do I need to add a delay in my code because its not finished generating the plot area before I try to resize it
The comment Rory made about reading the value solved the issue, strange that this is needed though..
Dim temp As Integer
With myChart.PlotArea
temp = .Top
temp = .Height
.Top = 70
.Height = 420
End With
I think the problem why your code return error because PlotArea properies can only be modify after the Chart object if fully loaded. So yes, you need to complete Chart Object loading process and modify any PlotArea properties.
The code below will work. Try it..!
Option Explicit
Public Sub Demo()
Dim maxPie As Long
Dim myChart As Chart
'I assume that your chart is on Sheet1
maxPie = Sheet1.Range("A1048576").End(xlUp).Row
Set myChart = Sheet1.Shapes.AddChart2.Chart
With myChart
.ChartType = xlBarClustered
.SetSourceData Source:=Range("Sheet1!$B$2:$C$" & maxPie)
End With
With myChart.Parent
.Top = 10
.Left = 500
.Width = 500
.Height = 500
End With
'Delay the SetPlotArea code execution using OnTime function
Application.OnTime Now, "SetPlotArea", Now + TimeValue("0:0:5")
End Sub
Public Sub SetPlotArea()
Dim ch As Chart
Set ch = Sheet1.ChartObjects(1).Chart
ch.PlotArea.Top = 70
ch.PlotArea.Height = 420
End Sub
i have problem with selecting combobox after creating it via shapes object. Can someone please help?
My code is
Dim comboBoxRange As Range
Set comboBoxRange = Sheets(axleDataWindowName).Range("F2:F4")
currentSheet.DropDowns.Add(20, 40, 100, 15).Name = "modifiedComboBox"
With currentSheet.Shapes("modifiedComboBox")
.Left = 450
.List comboBoxRange.Value
End With
You need to call currentSheet.Dropdowns("modifiedComboBox") instead of currentSheet.Shapes("modifiedComboBox"). Also use .AddItem instead of .List:
Dim comboBoxRange As Range
Set comboBoxRange = Sheets(axleDataWindowName).Range("F2:F4")
currentSheet.DropDowns.Add(20, 40, 100, 15).Name = "modifiedComboBox"
With currentSheet.Shapes("modifiedComboBox")
.Left = 450
.AddItem comboBoxRange.Value
End With
I'm adding ".jpg" files to my Excel sheet with the code below :
'Add picture to excel
xlApp.Cells(i, 20).Select
xlApp.ActiveSheet.Pictures.Insert(picPath).Select
'Calgulate new picture size
With xlApp.Selection.ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
'Resize and make printable
With xlApp.Selection
.Placement = 1 'xlMoveAndSize
'.Placement = 2 'xlMove
'.Placement = 3 'xlFreeFloating
.PrintObject = True
End With
I don't know what I am doing wrong but it doesn't get inserted into the right cell, so what should I do to put this picture into a specified cell in Excel?
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture in their code, only .Pictures.Insert()
Dim myPic As Object
Dim picpath As String
picpath = "C:\Users\photo.jpg" 'example photo path
Set myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)
With myPic
.Width = 25
.Height = 25
.Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer
.Left = xlApp.Cells(i, 20).Left
.LockAspectRatio = msoFalse
End With
I'm working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture, because of error "Argument not optional". Looking at this You may ask why I set Height and Width as -1, but that doesn't matter cause of those parameters are set underneath between With brackets.
Hope it may be also useful for someone :)
If it's simply about inserting and resizing a picture, try the code below.
For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.
Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.
Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
Dim Pic As Picture, Shp as Shape
Set Pic = wsDestination.Pictures.Insert(FilePath)
Pic.Name = "myPicture"
'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
Set Shp = wsDestination.Shapes("myPicture")
With Shp
.Height = 100
.Width = 75
.LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa)
.Placement = 1
.Top = 100
.Left = 100
End with
End Sub
Good luck!
I have been working on a system that ran on a PC and Mac and was battling to find code that worked for inserting pictures on both PC and Mac. This worked for me so hopefully someone else can make use of it!
Note: the strPictureFilePath and strPictureFileName variables need to be set to valid PC and Mac paths Eg
For PC: strPictureFilePath = "E:\Dropbox\" and strPictureFileName = "TestImage.jpg" and with Mac: strPictureFilePath = "Macintosh HD:Dropbox:" and strPictureFileName = "TestImage.jpg"
Code as Follows:
On Error GoTo ErrorOccured
shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Select
ActiveSheet.Pictures.Insert(Trim(strPictureFilePath & strPictureFileName)).Select
Selection.ShapeRange.Left = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Left
Selection.ShapeRange.Top = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Top + 10
Selection.ShapeRange.LockAspectRatio = msoTrue
Selection.ShapeRange.Height = 130
Firstly, of all I recommend that the pictures are in the same folder as the workbook.
You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son
For Each pic In ActiveSheet.Pictures
If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
pic.Delete
End If
Next pic
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width
son:
End Sub
With the codes above, the picture is sized according to the cell it is added to.
Details and sample file here : Vba Insert image to cell
I tested both #SWa and #Teamothy solution. I did not find the Pictures.Insert Method in the Microsoft Documentations and feared some compatibility issues. So I guess, the older Shapes.AddPicture Method should work on all versions. But it is slow!
On Error Resume Next
'
' first and faster method (in Office 2016)
'
With ws.Pictures.Insert(Filename:=imageFileName, LinkToFile:=msoTrue, SaveWithDocument:=msoTrue)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = destRange.Width
.height = destRange.height '222
End With
.Left = destRange.Left
.Top = destRange.Top
.Placement = 1
.PrintObject = True
.Name = imageName
End With
'
' second but slower method (in Office 2016)
'
If Err.Number <> 0 Then
Err.Clear
Dim myPic As Shape
Set myPic = ws.Shapes.AddPicture(Filename:=imageFileName, _
LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
Left:=destRange.Left, Top:=destRange.Top, Width:=-1, height:=destRange.height)
With myPic.OLEFormat.Object.ShapeRange
.LockAspectRatio = msoTrue
.Width = destRange.Width
.height = destRange.height '222
End With
End If