Copy and paste shape from one sheet to another - copy

Can someone tell me why this excel VBA to copy and paste a shape from one sheet to another fails? The shape "StandingsPix" and sheet "Pictures" exist in my workbook and in fact when I record a macro to do this manually, it creates similar code.
It fails in the assignment of "p" with "Object Variable Not Set". Help greatly appreciated.
Sub CopyPictureToScorecard(TargetCells As Range)
Dim p As Shape
Dim p2 As Shape
Dim TargetWS As Worksheet
Set TargetWS = Sheets("Scorecards")
p = Sheets("Pictures").Shapes.Range(Array("StandingsPix")) <== Fails Here
p.Copy
TargetWS.Paste
'make sure the picture is properly centered on the scorecard
Set p2 = TargetWS.Shapes(TargetWS.Shapes.Count)
p2.Width = p.Width
p2.Height = p.Height
p2.Top = TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2)
p2.Left = TargetCells.Left + (TargetCells.Width / 2) - (p2.Width / 2)
p2.Line.Visible = False
End Sub
When I record a macro doing this manually (successfully!), here is the code that it generated:
Sheets("Pictures").Select
ActiveSheet.Shapes.Range(Array("StandingsPix")).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Scorecards").Select
Range("K24").Select
ActiveSheet.Paste
Selection.ShapeRange.IncrementLeft 621
Selection.ShapeRange.IncrementTop -369.75

Sub CopyPictureToScorecard(TargetCells As Range)
Dim p As Shape
Set p = Sheets("Pictures").Shapes("StandingsPix")
Sheets("ScoreCards").Shapes.AddShape _
Type:=p.AutoShapeType, _
Left:=TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2), _
Top:=TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2), _
Width:=p.Width, _
Height:=p.Height
End Sub

Related

Libre Office custom Dialog Table

I am creating a custom Dialog where the user is supposed to select one of multiple possible entries. I use a List Box to list the possible entries to be selected from.
There are multiple variables for each row, therefore I would like to use a table to properly align the entries. Is there a possibility to do so?
What i have:
abcdefg hijkl mnopq
abcd efghijk lmno
What i want:
abcdefg hijkl mnopq
abcd efghilkl mno
Use a fixed-width font for the list box, and pad the strings with spaces.
Sub PaddedListboxItems
oListBox.addItems(Array(
PaddedItem(Array("abcdefg", "hijkl", "mnopq")),
PaddedItem(Array("abcd", "efghijk", "lmno"))), 0)
End Sub
Function PaddedItem(item_strings As Array)
PaddedItem = PadString(item_strings(0), 10) & _
PadString(item_strings(1), 11) & item_strings(2)
End Function
Function PadString(strSource As String, lPadLen As Long)
PadString = strSource & " "
If Len(strSource) < lPadLen Then
PadString = strSource & Space(lPadLen - Len(strSource))
End If
End Function
More ways to pad strings in Basic are at http://www.tek-tips.com/viewthread.cfm?qid=522164, although not all of them work in LibreOffice Basic.
Yes, it is possible.
Create a new dialog and at the bottom, add a label.
Create a new module and add following code:
Option Explicit
Option Base 0
Dim oDialog1 As Object, oDataModel As Object, oListener As Object
Sub OpenDialog()
Dim oGrid As Object, oGridModel As Object, oColumnModel As Object, oCol As Object
Dim oLabel1 As Object, rect(3) As Integer
DialogLibraries.LoadLibrary("Standard")
oDialog1 = CreateUnoDialog(DialogLibraries.Standard.Dialog1)
oGridModel = oDialog1.getModel().createInstance("com.sun.star.awt.grid.UnoControlGridModel")
oLabel1 = oDialog1.getModel().getByName("Label1")
rect(0) = oLabel1.getPropertyValue("PositionX")
rect(1) = 10
rect(2) = oLabel1.getPropertyValue("Width")
rect(3) = oLabel1.getPropertyValue("PositionY") - 2*rect(1)
With oGridModel
.PositionX = rect(0)
.PositionY = rect(1)
.Width = rect(2)
.Height = rect(3)
End With
oColumnModel = oGridModel.ColumnModel
oCol = oColumnModel.createColumn()
oCol.Title = "Column 1"
oColumnModel.addColumn(oCol)
oCol = oColumnModel.createColumn()
oCol.Title = "Column 2"
oColumnModel.addColumn(oCol)
oCol = oColumnModel.createColumn()
oCol.Title = "Column 3"
oColumnModel.addColumn(oCol)
oDialog1.getModel().insertByName("grid", oGridModel)
oGrid = oDialog1.getControl("grid")
oListener = (CreateUnoListener("grid_", "com.sun.star.awt.grid.XGridSelectionListener"))
oGrid.addSelectionListener(oListener)
oDataModel = oGridModel.GridDataModel
oDataModel.addRow("a", Array("abcdefg", "hijkl", "mnopq"))
oDataModel.addRow("b", Array("abcd", "efghijk", "lmno"))
oDialog1.execute()
oDialog1.dispose()
End Sub
To get the values of the selected row, add a listener for the grid_selectionChanged event:
Sub grid_selectionChanged(ev)
Dim oRows() As Object, oLabel1 As Object, sCells(2) As String
oRows = ev.Source.getSelectedRows()
oLabel1 = oDialog1.getModel().getByName("Label1")
sCells(0) = oDataModel.getRowData(oRows(0))(0)
sCells(1) = oDataModel.getRowData(oRows(0))(1)
sCells(2) = oDataModel.getRowData(oRows(0))(2)
oLabel1.setPropertyValue("Label", "Selected values: " + sCells(0) + "," + sCells(1) + "," + sCells(2))
End Sub
If you did all correctly, by running OpenDialog you should get your grid:

custom data validation in a VBA form

I have this form to enter new data to a table.
I would like to warn the user when he is entering an invoice number that already exist. Here is the code I have but its not working:
Private Sub CommandButton1_Click()
Dim L As Long
Dim Code As String
Dim TextBox2 As Long
Dim valFormula As String
valFormula = "=COUNTIFS($F12:$F1702,F1702,$D12:$D1702,D1702)=1"
If MsgBox("Confirm?", vbYesNo, "Confirming new invoice") = vbYes Then
With Worksheets("FACTURE")
L = Sheets("FACTURE").Range("D65535").End(xlUp).Row + 1 'Pour placer le nouvel enregistrement _ la premi_re ligne de tableau non vide
End With
With Me
Range("D" & L).Validation
.Add Type:=xlValidateCustom, _
AlertStyle:=xlValidAlertWarning, _
Formula1:="=COUNTIFS($F12:$F1702,F1702,$D12:$D1702,D1702)=1"
.InputTitle = ""
.ErrorTitle = "Duplicate alert"
.InputMessage = ""
.ErrorMessage = "This invoice number already exist. Continue?"
Range("B" & L).Value = .ComboBox2 & .ComboBox3
Range("C" & L).Value = (Now)
Range("D" & L).Value = .TextBox2
Range("E" & L).Value = .TextBox3
Range("F" & L).Value = .TextBox4
Range("G" & L).Value = .TextBox5
Range("K" & L).Value = .ComboBox1
Range("L" & L).Value = .ComboBox2
Range("M" & L).Value = .ComboBox3
Range("N" & L).Value = .TextBox9
Range("O" & L).Value = .TextBox10
Range("R" & L).Value = .TextBox39
Range("P" & L).Value = .TextBox40
Range("C" & L).Interior.ColorIndex = 0
If .OptionButton1 Then
FormatCell Range("B" & L), xlThemeColorAccent3
ElseIf .OptionButton2 Then
FormatCell Range("B" & L), xlThemeColorAccent1
ElseIf .OptionButton3 Then
FormatCell Range("B" & L), xlThemeColorAccent4
Else
FormatCell Range("B" & L), xlThemeColorAccent2
End If
End With
End If
End Sub
Any advice?
As Comintern suggested, use Find() method of Range object, with code like:
Set f = rngToSerachIn.Find(what:=factureNo, LookIn:=xlValues, lookat:=xlWhole)
where
f is a range variable where to store the range with the searched value
rngToSerachIn is the range where to search the value
factureNo is the value to search for
furthermore it seems to me your invoices will be stored in rows from 12 downwards, so it could be useful to write a generic function to get first empty cell in a given column of a given worksheet ranging from a certain row
Since it'd be a good practice to demand specific tasks to Sub/Function to improve both code readability and maintenance, you could do that for:
getting first empty row after last non empty one starting from a given row in a given column of a given worksheet
validating invoice number
filling worksheet ranges
formatting invoice cell
as follows:
Option Explicit
Private Sub CommandButton1_Click()
Dim L As Long
Dim factureWs As Worksheet
If MsgBox("Confirm?", vbYesNo, "Confirming new invoice") = vbNo Then Exit Sub
Set factureWs = Worksheets("FACTURE") '<--| set the worksheet you want to work with
L = GetLastNonEmptyRow(factureWs, "D", 12) + 1 '<--| get passed worksheet first empty row after last non empty one in column "D" from row 12 (included)
If L > 12 Then If Not CheckDuplicate(Me.TextBox2, factureWs.Range("D12:D" & L - 1)) Then Exit Sub '<--| exit if duplicated non accepted by the user
FillRanges factureWs, L '<--| fill worksheet ranges with userfom controls values
FormatInvoice factureWs.Range("B" & L) '<--| color invoice cell depending on option buttons values
End Sub
Function GetLastNonEmptyRow(ws As Worksheet, colIndex As String, firstRow As Long) As Long
Dim lastRow As Long
With ws
lastRow = .Cells(.Rows.Count, colIndex).End(xlUp).row ' <--| get last non empty row in given column
If lastRow = 1 Then If IsEmpty(.Range(colIndex & 1)) Then lastRow = 0 '<--| handle the case of an empty column
If lastRow < firstRow Then lastRow = firstRow - 1 '<--| handle the case the last non empty row is above the first passed one
End With
GetLastNonEmptyRow = lastRow
End Function
Function CheckDuplicate(factureNo As String, rng As Range) As Boolean
Dim f As Range
Set f = rng.Find(what:=factureNo, LookIn:=xlValues, lookat:=xlWhole)
If Not f Is Nothing Then
CheckDuplicate = MsgBox("This invoice number already exist!" & vbCrLf & vbCrLf & "Continue?", vbExclamation + vbYesNo, "Duplicate alert") = vbYes
Else
CheckDuplicate = True
End If
End Function
Sub FormatInvoice(rng As Range)
Dim thColor As XlThemeColor
With Me
Select Case True
Case .OptionButton1
thColor = xlThemeColorAccent3
Case .OptionButton2
thColor = xlThemeColorAccent1
Case .OptionButton3
thColor = xlThemeColorAccent4
Case Else
thColor = xlThemeColorAccent2
End Select
End With
FormatCell rng, thColor
End Sub
Sub FillRanges(ws As Worksheet, L As Long)
With ws
.Range("C" & L).Value = (Now)
.Range("D" & L).Value = Me.TextBox2
.Range("E" & L).Value = Me.TextBox3
.Range("F" & L).Value = Me.TextBox4
.Range("G" & L).Value = Me.TextBox5
.Range("K" & L).Value = Me.ComboBox1
.Range("L" & L).Value = Me.ComboBox2
.Range("M" & L).Value = Me.ComboBox3
.Range("N" & L).Value = Me.TextBox9
.Range("O" & L).Value = Me.TextBox10
.Range("R" & L).Value = Me.TextBox39
.Range("P" & L).Value = Me.TextBox40
End With
End Sub
you may find it useful and follow this pattern in your subsequent coding

Excel Range object throws error 0x800A03EC because of a string longer than 255 characters

Using an ActiveX server from MATLAB, I am trying to highlight many cells in an Excel sheet at once. These are not in specific columns or rows so I use Range('A1,B2,...') to access them. However the string accepted by the Range object has to be less than 255 characters or an error:
Error: Object returned error code: 0x800A03EC
is thrown. The following code reproduces this error with an empty Excel file.
hActX = actxserver('Excel.Application');
hWB = hActX.Workbooks.Open('C:\Book1.xlsx');
hSheet = hWB.Worksheets.Item('Sheet1');
col = repmat('A', 100, 1);
row = num2str((1:100)'); %'
cellInd = strcat(col, strtrim(cellstr(row)));
str1 = strjoin(cellInd(1:66), ','); %// 254 characters
str2 = strjoin(cellInd(1:67), ','); %// 258 characters
hSheet.Range(str1).Interior.Color = 255; %// Works
hSheet.Range(str2).Interior.Color = 255; %// Error 0x800A03EC
hWB.Save;
hWB.Close(false);
hActX.Quit;
How can I get around this? I found no other relevant method of calling Range, or of otherwise getting the cells I want to modify.
If you start with a String, you can test its length to determine if Range() can handle it. Here is an example of building a diagonal range:
Sub DiagonalRange()
Dim BigString As String, BigRange As Range
Dim i As Long, HowMany As Long, Ln As String
HowMany = 100
For i = 1 To HowMany
BigString = BigString & "," & Cells(i, i).Address(0, 0)
Next i
BigString = Mid(BigString, 2)
Ln = Len(BigString)
MsgBox Ln
If Ln < 250 Then
Set BigRange = Range(BigString)
Else
Set BigRange = Nothing
arr = Split(BigString, ",")
For Each a In arr
If BigRange Is Nothing Then
Set BigRange = Range(a)
Else
Set BigRange = Union(BigRange, Range(a))
End If
Next a
End If
BigRange.Select
End Sub
For i = 10, the code will the the direct method, but if the code were i=100, the array method would be used.
The solution, as Rory pointed out, is to use the Union method. To minimize the number of calls from MATLAB to the ActiveX server, this is what I did:
str = strjoin(cellInd, ',');
isep = find(str == ',');
isplit = diff(mod(isep, 250)) < 0;
isplit = [isep(isplit) (length(str) + 1)];
hRange = hSheet.Range(str(1:(isplit(1) - 1)));
for ii = 2:numel(isplit)
hRange = hActX.Union(hRange, ...
hSheet.Range(str((isplit(ii-1) + 1):(isplit(ii) - 1))));
end
I used 250 in the mod to account for the cell names being up to 6 characters long, which is sufficient for me.

VBA Excel make array of sequential numbers

I am working in VBA for Excel at the moment but am really only versed in Matlab. It's important for my work to stay in the memory of vba (not on the worksheets of excel) for time purposes.
What I need to do is make an array of sequential integers, say 4000 through 5000.
In matlab this is really easy, I would just do... i = 4000:5000, or i=4000:1:5000. With the 1 in the second case being my 'step.'
I was wondering what is the best way to achieve this result in vba?
Thanks
Without looping - Just seen Rory's same answer above after posting
Sub MakeArray()
Dim x As Long, y As Long, arr As Variant
x = 4000: y = 5000
arr = Evaluate("Row(" & x & ":" & y & ")")
'Show result
Sheets(1).Range("A1").Resize(y - x + 1) = arr
End Sub
The following is an example of creating and then displaying a set of sequential numbers:
Sub seqnum()
Dim firstnum As Long, secnum As Long
firstnum = 7
secnum = 23
ReDim ary(1 To secnum - firstnum + 1) As Long
For i = 1 To UBound(ary)
ary(i) = firstnum + (i - 1)
Next i
msg = ""
For i = 1 To UBound(ary)
msg = msg & i & vbTab & ary(i) & vbCrLf
Next i
MsgBox msg
End Sub
I Us "Fill" - "Series":
Write in first cell number ex. 400 and in the "Series" window insert increment step and in "Stop Value" last value. ex. 420
Or with Macro
Range("I1").Select
ActiveCell.FormulaR1C1 = "4000"
Range("I1").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=4020, Trend:=False

Email excel data range when target cell changes

This macro works on line 5 ,so i need this macro to work on all lines in one sheet instead of one macro for each line. Row X and email range A:L are copy paste in all lines i.e.( X1 A1:L1 | X2 ,A2:L2 ...)
Dim X5 As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("X5").Value = 1 And X5 <> 1 Then
ActiveSheet.Range("A5:L5").Select
ActiveWorkbook.EnvelopeVisible = True
With ActiveSheet.MailEnvelope
.Introduction = " send thru macro "
.Item.To = "email#gmail.com"
.Item.Subject = "ALERT"
.Item.Send
End With
End If
X5 = Range("X5").Value
End Sub
Not sure if you got your answer or not so I am attempting to answer this question.
To make it flexible for any row, you can store the row of the current cell in a variable using Target.Row and then simply use that to construct your range.
Also to understand how Worksheet_Change works, you may want to see THIS
Is this what you are trying?
Dim X5 As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
'~~> Check if the chnage happened to multiple cells
If Target.cell.CountLarge > 1 Then Exit Sub
Dim Rw As Long
'~~> Get the row number of the cell that was changed
Rw = Target.Row
If Range("X" & Rw).Value = 1 And X5 <> 1 Then
Application.EnableEvents = False
Range("A" & Rw & ":L" & Rw).Select
ActiveWorkbook.EnvelopeVisible = True
With ActiveSheet.MailEnvelope
.Introduction = " send thru macro "
.Item.To = "email#gmail.com"
.Item.Subject = "ALERT"
.Item.Send
End With
End If
X5 = Range("X" & Rw).Value
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub