I have created a UserForm with some textboxes and comboboxes inside, the data that is typed in textboxes are supposed to be inserted in cell in the sheet, the determation of which cell is based on the value in ComboBox4. unfortunately the code keeps giving me error: "Run-time error '13': Type mismatch" and I have not been able to find out what is going wrong?
if someone knows what the problem is please let me know.
Private Sub UserForm_Initialize()
ComboBox3.List = [ADMIN!e2:E1000].Value
ComboBox4.List = [PRODUCTION!O6:O1000].Value
End Sub
Private Sub ACCEPTBUTTON_Click()
Application.ScreenUpdating = False
Worksheets("PRODUCTION").Activate
Dim C As Long
For C = 1000 To 1 Step -1
If Cells(C + 1, 1) Like ComboBox4 Then
Cells(C + 1, 1).EntireRow.Select
Selection.EntireRow.Hidden = False
Application.CutCopyMode = False
End If
Next C
Range("AC" & (ActiveCell.Row)).Value = TextBox1.Value
Range("AD" & (ActiveCell.Row)).Value = TextBox2.Value
Range("AE" & (ActiveCell.Row)).Value = TextBox3.Value
Range("AF" & (ActiveCell.Row)).Value = TextBox4.Value
Range("AG" & (ActiveCell.Row)).Value = TextBox5.Value
Range("AH" & (ActiveCell.Row)).Value = TextBox6.Value
Range("AI" & (ActiveCell.Row)).Value = TextBox7.Value
Range("AJ" & (ActiveCell.Row)).Value = TextBox8.Value
ActiveCell.EntireRow.RowHeight = 16
Unload Me
Application.ScreenUpdating = True
End Sub
Here's some commented code that should work for you. I did find it strange that you populate the values in ComboBox4 from column O, but then search column A for matches, is that intentional? (In the provided code, it searches for matches from the same list as populated the combobox which will guarantee a match is found).
Also, instead of a 1000 long loop to find the matches, this uses a Range.Find loop to increase speed and efficiency.
'Declare userform variables that any of this userform's Subs can reference
Private wb As Workbook
Private wsAdm As Worksheet
Private wsPrd As Worksheet
Private rAdmList As Range
Private rPrdList As Range
Private Sub UserForm_Initialize()
'Populate userform variables
Set wb = ThisWorkbook
Set wsAdm = wb.Worksheets("ADMIN")
Set wsPrd = wb.Worksheets("PRODUCTION")
Set rAdmList = wsAdm.Range("E2", wsAdm.Cells(wsAdm.Rows.Count, "E").End(xlUp)) 'Dynamically size list
Set rPrdList = wsPrd.Range("O6", wsPrd.Cells(wsPrd.Rows.Count, "O").End(xlUp)) 'Dynamically size list
Me.ComboBox3.List = rAdmList.Value
Me.ComboBox4.List = rPrdList.Value
End Sub
Private Sub ACCEPTBUTTON_Click()
'Check if anything is selected from ComboBox4
If Me.ComboBox4.ListIndex = -1 Then
Me.ComboBox4.SetFocus
MsgBox "Must select a Production item"
Exit Sub
End If
'An item from the production list in combobox4 has been confirmed to be selected
'Search the corresonding ComboBox4 list range to find the corresponding row
'(In your original code, you are searching column A instead of the column that populated the combobox which is column O, is there a reason for that?)
Dim rFound As Range, sFirst As String
Set rFound = rPrdList.Find(Me.ComboBox4.Text, rPrdList(rPrdList.Cells.Count), xlValues, xlWhole)
If Not rFound Is Nothing Then
sFirst = rFound.Address 'Record first address of found item
Do
'Matching row found, unhide and populate cells with textbox values
'Note that there is currently no check or validation that the textboxes are populated
rFound.EntireRow.Hidden = False
wsPrd.Cells(rFound.Row, "AC").Value = Me.TextBox1.Text
wsPrd.Cells(rFound.Row, "AD").Value = Me.TextBox2.Text
wsPrd.Cells(rFound.Row, "AE").Value = Me.TextBox3.Text
wsPrd.Cells(rFound.Row, "AF").Value = Me.TextBox4.Text
wsPrd.Cells(rFound.Row, "AG").Value = Me.TextBox5.Text
wsPrd.Cells(rFound.Row, "AH").Value = Me.TextBox6.Text
wsPrd.Cells(rFound.Row, "AI").Value = Me.TextBox7.Text
wsPrd.Cells(rFound.Row, "AJ").Value = Me.TextBox8.Text
'Search for next cell that matches
Set rFound = rPrdList.FindNext(rFound)
Loop While rFound.Address <> sFirst 'Loop until back at first address
Else
'If the item wasn't found, it's because the user manually typed in something in the combobox, or other error occurred
Me.ComboBox4.SetFocus
MsgBox "Invalid value entered for Production item"
Exit Sub
End If
Unload Me
End Sub
I have been using this code which works for some URL but not for all I really do not why. Then I have tried with different available codes online but no success.
Your help will be really appreciated in this regards.
Option Explicit
Dim rng As Range
Dim cell As Range
Dim Filename As String
Sub URLPictureInsert()
Dim theShape As Shape
Dim xRg As Range
Dim xCol As Long
On Error Resume Next
Application.ScreenUpdating = False
Set rng = ActiveSheet.Range("A1:A3000") ' <---- ADJUST THIS
For Each cell In rng
Filename = cell
If InStr(UCase(Filename), "JPG") > 0 Then ' <--- USES JPG ONLY
ActiveSheet.Pictures.Insert(Filename).Select
Set theShape = Selection.ShapeRange.Item(1)
If theShape Is Nothing Then GoTo isnill
xCol = cell.Column + 1
Set xRg = Cells(cell.Row, xCol)
With theShape
.LockAspectRatio = msoFalse
.Width = 20
.Height = 20
.Top = xRg.Top + (xRg.Height - .Height) / 2
.Left = xRg.Left + (xRg.Width - .Width) / 2
End With
isnill:
Set theShape = Nothing
Range("A2").Select
End If
Next
Application.ScreenUpdating = True
Debug.Print "Done " & Now
End Sub
URL's
https://s3-eu-west-1.amazonaws.com/images.linnlive.com/a93f20bbb3640a1a7dc9b9a05bee8540/fc310885-cd82-49cb-bc7a-aabd08531517.jpg
https://s3-eu-west-1.amazonaws.com/images.linnlive.com/a93f20bbb3640a1a7dc9b9a05bee8540/c6c7a645-8273-40ee-87e5-1dd385111a28.jpg
https://s3-eu-west-1.amazonaws.com/images.linnlive.com/a93f20bbb3640a1a7dc9b9a05bee8540/cf9f971b-6af6-4894-a2d5-c58681adb466.jpg
Try this code below, it will Debug.Print the URL that fails to insert. Adapt to your need (if any)
Sub URLPictureInsert()
Dim rng As Range
Dim cell As Range
Application.ScreenUpdating = False
With ActiveSheet
Set rng = .Range("A2:A" & .Range("A" & .Rows.Count).End(xlUp).Row) ' <---- ADJUST THIS
End With
For Each cell In rng
If InStr(UCase(cell), "JPG") > 0 Then '<--- ONLY USES JPG'S
With cell.Offset(0, 1)
On Error Resume Next
ActiveSheet.Shapes.AddPicture cell, msoFalse, msoTrue, .Left + (.Width - 10) / 2, .Top + (.Height - 10) / 2, 20, 20
If Err.Number = 1004 Then Debug.Print "File not found: " & cell
On Error GoTo 0
End With
End If
Next
Application.ScreenUpdating = True
Debug.Print "Done " & Now
End Sub
You will need to use On Error Resume Next, but only for the single statement that inserts the picture. And you should get rid of the Select. The Pictures.Insert-method returns the reference to the inserted image, assign this to a variable and work with that.
Additionally, I would suggest to split your code and create a routine that insert one image into a cell. Call this routine from the loop. I have implemented it as a function that returns True if it was successfull, it's up to you to decide if you want to do something if it returns False.
Function TryInsertImg(filename As String, cell As Range) As Boolean
Dim p As Picture
On Error Resume Next
Set p = cell.Parent.Pictures.Insert(filename)
If Err.Number > 0 Then Debug.Print "Couldn't insert image " & Err.Number & "-" & Err.Description
On Error GoTo 0
If p Is Nothing Then
Exit Function
End If
Dim theShape As Shape
Set theShape = p.ShapeRange.Item(1)
With theShape
.LockAspectRatio = msoFalse
.Width = 20
.Height = 20
.Top = cell.Top + (cell.Height - .Height) / 2
.Left = cell.Left + (cell.Width - .Width) / 2
End With
TryInsertImg = True
End Function
Your calling routine could look like this:
For Each cell In rng
Filename = cell
If InStr(UCase(Filename), "JPG") > 0 Then '<--- ONLY USES JPG'S
xCol = cell.Column + 1
Set xRg = Cells(cell.Row, xCol)
If Not TryInsertImg(filename, xRg) then
xRg = "(error loading image)"
End If
End If
Next cell
Good afternoon to all.
I now need be able to send the formatted textbox back to the originating active cell.
This code was copy format from cell to textbox, I now need to reverse this process
Sub passCharToTextbox()
CopycellFormat ActiveCell
End Sub
Private Sub CopycellFormat(cell As Range)
If Trim(cell(1, 1).Value) = vbNullString Then MsgBox ("select only cell / not emptycell"): Exit Sub
Dim textrange As TextRange2, tbox1 As Shape, fontType As Font2
With ActiveSheet
On Error Resume Next: Err.Clear 'check if Textbox 2 exist
Set tbox1 = .Shapes("Textbox 2"): Set textrange = tbox1.TextFrame2.textrange
textrange.Characters.Text = cell.Value
If Err.Number > 0 Then MsgBox ("Not found Textbox 2")
For i = 1 To Len(cell.Value)
Set fontType = textrange.Characters(i, 1).Font
With cell.Characters(i, 1)
fontType.Bold = IIf(.Font.Bold, True, 0) 'add bold/
fontType.Italic = IIf(.Font.Italic, True, 0) 'add italic/
fontType.UnderlineStyle = IIf(.Font.Underline > 0, msoUnderlineSingleLine, msoNoUnderline) 'add underline/
textrange.Characters(i, 1).Font.Fill.ForeColor.RGB = .Font.Color 'add Font color
End With
Next i
tbox1.Fill.ForeColor.RGB = cell.Interior.Color 'add background color
End With
End Sub
Many thanks for taking the time to read, and please everyone, stay well.
focus on your problem:
First, make sure "textbox 2" exists
Then, Select the cell need to copy format and run the code CopyFormat_fromTextbox_toCell
Here's following code:
Sub CopyFormat_fromTextbox_toCell()
CopycellFormat1 activecell
End Sub
Private Sub CopycellFormat1(cell As Range)
Dim textrange As TextRange2, tbox1 As Shape, fontType As Font2, cellfont As Font
With ActiveSheet
Set tbox1 = .Shapes("Textbox 2"): Set textrange = tbox1.TextFrame2.textrange
cell.Value = textrange.Characters.Text
For i = 1 To Len(cell.Value)
Set fontType = textrange.Characters(i, 1).Font
Set cellfont = cell.Characters(i, 1).Font
With fontType
cellfont.Bold = IIf(.Bold, True, 0) 'add bold/
cellfont.Italic = IIf(.Italic, True, 0) 'add italic/
cellfont.Underline = IIf(.UnderlineStyle > 0, 2, -4142) 'add underline/
cellfont.Color = textrange.Characters(i, 1).Font.Fill.ForeColor.RGB 'add Font color
End With
Next i
cell.Interior.Color = tbox1.Fill.ForeColor.RGB 'add background color
End With
End Sub
In Excel VBA, I am running into an "error" that halts the macro and a message displays "Code execution has been interrupted." I wrote error in quotations because when I selected debug and examined the line of code that prompted the error, I saw that it was logically sound.
I originally ran into the error at On Error GoTo 0. When I comment out a block around the error, then I get a new line that produces the same error. And, again, when I examine it in debug mode the new "error" is logically sound. Here is the exact line:
If rRange.Row <> 3 And rRange.Row <> 17 Then
FYI, rRange.Row = 3 in this case, so it shouldn't produce an error.
Why is this happening and how can I fix it?
UPDATE Code now produces the error on the End Sub line.
Here is the section that fails:
Sub Review()
Dim WorkRange As Range
Dim FoundCells As Range
Dim Cell As Range
Dim a As String
Dim policy As String
Dim rRange As Range
Set RR = Sheets("Ready for Review")
Set OG = ActiveSheet
OG.Unprotect ("Password")
RR.Activate
On Error Resume Next
Application.DisplayAlerts = False
Set rRange = Application.InputBox(Prompt:= _
"Please select POLICY to review.", _
Title:="SPECIFY POLICY", Type:=8)
On Error GoTo 0
Application.DisplayAlerts = True
If rRange.Row <> 3 And rRange.Row <> 17 Then
MsgBox "Value other than a POLICY was selected. Select the cell that contains the correct policy number."
Exit Sub
Else
policy = rRange.Value
End If
Application.ScreenUpdating = False
OG.Cells(12, 2).Locked = False
Set WorkRange = OG.UsedRange
For Each Cell In WorkRange
If Cell.Locked = False Then
col1 = Cell.Column
Row = Cell.Row
a = OG.Cells(Row, 1)
If Not a = "" Then
row2 = Application.WorksheetFunction.Match(a, RR.Range("A:A"), 0)
Cell.Value = RR.Cells(row2, rRange.Column + col1 - 2)
End If
End If
Next Cell
OG.Unprotect ("Password")
OG.Cells(33, 3).Locked = False
If (Right(OG.Cells(5, 2), 2) = "UL" Or Right(OG.Cells(5, 2), 2) = "IL" Or Right(OG.Cells(5, 2), 2) = "PL") Then
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""Total*"",A:A,0)))-SUM(C34:C37)"
.Locked = True
End With
ElseIf Right(OG.Cells(5, 2), 2) = "WL" Then
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0))) - IFERROR(INDEX(C34:C37,MATCH(""Additional"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Paid"",B34:B37,0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Additional Agreement - SPPUA"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Flexible Agreement - FLXT10/20"",B34:B37, 0)),0)"
.Locked = True
End With
Else
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0)))"
.Locked = True
End With
End If
OG.Activate
Cells(Application.WorksheetFunction.Match("Last Month Paid ($)", Range("A:A"), 0), 2).NumberFormat = "$#,##0.00;[Red]$#,##0.00"
OG.Protect ("Password")
Application.ScreenUpdating = True
End Sub
Oh, that brings back memories for me. I think I used to get this error about 10 years ago Excel 2003? Maybe?. Excel would get itself into a bit of a state. Nothing was wrong with the code, just it would keep coming back with that error.
If you save your work close Excel and then reopen, does the error go away?
If I remember right, it was caused when I called some external API. Maybe some other API call in your is causing this error but manifesting at this point... perhaps.
Sorry but it was 10+ years ago :)
even if you went through it, you may want to consider the following "restyling" of the code you posted
Option Explicit
Sub Review()
Dim Cell As Range, rRange As Range
Dim a As String
Dim RR As Worksheet, OG As Worksheet
Set RR = Sheets("Ready for Review")
Set OG = ActiveSheet
OG.Unprotect ("Password")
Set rRange = GetUserInpt(RR)
If rRange Is Nothing Then
MsgBox "You aborted the POLICY selection" _
& vbCrLf & vbCrLf _
& "the procedure ends" _
, vbInformation
Exit Sub
End If
Application.ScreenUpdating = False
OG.Cells(12, 2).Locked = False
For Each Cell In OG.UsedRange
With Cell
If Not .Locked Then
a = OG.Cells(.row, 1)
If Not a = "" Then .value = RR.Cells(CLng(Application.WorksheetFunction.Match(a, RR.Range("A:A"), 0)), _
rRange.Column + .Column - 2)
End If
End With
Next Cell
With OG.Cells(33, 3)
.Locked = False
Select Case Right(OG.Cells(5, 2), 2)
Case "UL", "IL", "PL"
.Formula = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""Total*"",A:A,0)))-SUM(C34:C37)"
Case "WL"
.Formula = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0))) - IFERROR(INDEX(C34:C37,MATCH(""Additional"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Paid"",B34:B37,0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Additional Agreement - SPPUA"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Flexible Agreement - FLXT10/20"",B34:B37, 0)),0)"
Case Else
.value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0)))"
End Select
.Locked = True
End With
OG.Activate
Cells(Application.WorksheetFunction.Match("Last Month Paid ($)", Range("A:A"), 0), 2).NumberFormat = "$#,##0.00;[Red]$#,##0.00"
OG.Protect ("Password")
Application.ScreenUpdating = True
End Sub
Function GetUserInpt(sht As Worksheet) As Range
Dim rRange As Range
Application.DisplayAlerts = False
sht.Activate
On Error GoTo InputBoxCanceled
Do While rRange Is Nothing
Set rRange = Application.InputBox(Prompt:="Please select POLICY to review.", _
Title:="SPECIFY POLICY", _
Default:=sht.Cells(3, 1).Address, _
Type:=8)
If rRange.Parent.Name <> sht.Name Then
MsgBox "You must select a cell in '" & sht.Name & "' sheet"
sht.Activate
Set rRange = Nothing
Else
If rRange.row <> 3 And rRange.row <> 17 Then
MsgBox "Value other than a POLICY was selected" _
& vbCrLf & vbCrLf _
& "Select the cell that contains the correct policy number" _
, vbCritical
Set rRange = Nothing
End If
End If
Loop
Set GetUserInpt = rRange
InputBoxCanceled:
On Error GoTo 0
Application.DisplayAlerts = True
End Function
the main revision applies to:
added a GetUserInpt function to handle the policy selection
this function:
checks for both the correct selection row and sheet, too (since it's possible the user shifts to another worksheet during selection!)
runs a loop until the user selects a proper cell
exits selection upon user canceling the InputBox, as the only loop escape possibility
made some simplifications here and there, like:
eliminated Activate statements unless really needed
reduced the amount of variables to only (nearly) strictly needed ones
added some With ... End With blocks to add readability
used a Select Case block instead of an If ... Then ... Else if ... Else ... End if one, for readability again
changed .Value to .Formula, for a proper syntax
all what above could help you with this project and in future ones, too
I'm trying to help out a coworker with her VBA in Excel 2013. It looks like the macro is successfully pulling in the images from the designated path, but it dumps every single photo into cell A1.
Any thoughts?
Sub DeleteAllPictures()
Dim S As Shape
For Each S In ActiveSheet.Shapes
Select Case S.Type
Case msoLinkedPicture, msoPicture
S.Delete
End Select
Next
End Sub
Sub UpdatePictures()
Dim R As Range
Dim S As Shape
Dim Path As String, FName As String
'Setup the path
Path = "G:\In Transit\Carlos\BC Website images"
'You can read this value also from a cell, e.g.:
'Path = Worksheets("Setup").Range("B1")
'Be sure the path has a trailing backslash
If Right(Path, 1) <> "\" Then Path = Path & "\"
'Visit each used cell in column A
For Each R In Range("B1", Range("B" & Rows.Count).End(xlUp))
'Try to get the shape
Set S = GetShapeByName(R)
'Found?
If S Is Nothing Then
'Find the picture e.g. "C:\temp\F500.*"
FName = Dir(Path & R & ".*")
'Found?
If FName <> "" Then
Set S = InsertPicturePrim(Path & FName, R)
End If
End If
If Not S Is Nothing Then
'Show the error if the name did not match the cell
If S.Name <> R Then R.Interior.Color = vbRed
With R.Offset(0, 1)
'Move the picture to the cell on the right side
S.Top = .Top
S.Left = .Left
'Resize it
S.Width = .Width
'Remove the aspect ratio by default if necessary
'S.LockAspectRatio = False
If S.LockAspectRatio Then
'Make it smaller to fit the cell if necessary
If S.Height > .Height Then S.Height = .Height
Else
'Stretch the picture
S.Height = .Height
End If
End With
'Move it behind anything else
S.ZOrder msoSendToBack
Else
R.Offset(0, 1) = "No picture available"
End If
Next
End Sub
Private Function GetShapeByName(ByVal SName As String) As Shape
'Return the shape with SName, Nothing if not exists
On Error Resume Next
Set GetShapeByName = ActiveSheet.Shapes(SName)
End Function
Private Function InsertPicturePrim(ByVal FName As String, ByVal SName As String) As Shape
'Inserts the picture, return the shape, Nothing if failed
Dim P As Picture
On Error Resume Next
'Insert the picture
Set P = ActiveSheet.Pictures.Insert(FName)
'code to resize
With P
.ShapeRange.LockAspectRatio = msoFalse
.Height = ActiveCell.Height
.Width = ActiveCell.Width
.Top = ActiveCell.Top
.Left = ActiveCell.Left
.Placement = xlMoveAndSize
End With
Set P = Nothing
'code to resize
'Success?
If Not P Is Nothing Then
'Return the shape
Set InsertPicturePrim = P.ShapeRange(1)
'Rename it, so we can easily find it later
P.Name = SName
End If
End Function
The short answer is: your macro is inserting the picture at the selected cell. Change the selection before the insert line, and you should get it inserted at each row.
Here in this example, I am selecting the cell to the left of the cell you are pulling the name value from.
If FName <> "" Then
'select the cell 1 to the left of the cell containing the image name
R.Offset(0,-1).select
Set S = InsertPicturePrim(Path & FName, R)
End If