VBA .AddPicture with late binding Error 424 - vba

Using the below code i get a 424 error "Object Required" on the .AddPicure line as indicated. I'm unsure as to why as pic is dimensioned as object, and the .addpicture comand looks fully referenced to me.
Apologies for the length of code, i thought it best to leave in all variables.
I'm using Excel 13 from MS Visio 16, and late binding is necessary.
**Edit: Sorry, it is infact an add text box line thats giving me the problem, I've updated the code below...
Sub testexcel()
Dim pic As Object
Dim rng As Object
Dim tWidth As Long, tHeight As Long
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWb = xlApp.workbooks.Open("C:\Users\tom\Desktop\Book1.xlsx")
Set xlWs = xlWb.sheets("Sheet1")
xlApp.ScreenUpdating = False
Set rng = xlWs.Range("B18")
Set rng2 = xlWs.Range("A1", rng.Offset(-1, -1))
picture1 = "C:\Users\tom\Desktop\PX001.bmp"
pHeight = 145
pWidth = 200
tHeight = 10
tWidth = 200
posX = 10
posY = 10
'On Error GoTo ErrMsg
With xlWs.Range("A1", rng.Offset(-1, -1))
'*******Problem on next line*******
Set txtBx = xlWs.Shapes.AddTextbox(msoTextOrientationHorizontal,
txtPosX, txtPosY, tWidth, tHeight).TextFrame.Characters.Text = "FooBar"
End With
'Some other code here...
End Sub

try splitting it up
Set txtBx = xlWs.Shapes.AddTextbox(msoTextOrientationHorizontal, txtPosX, txtPosY, tWidth, tHeight)
txtBx.TextFrame.Characters.Text = "FooBar"
I think this is what's happening:
xlWs.Shapes.AddTextbox(msoTextOrientationHorizontal, txtPosX, txtPosY, tWidth, tHeight).TextFrame.Characters.Text = "FooBar"
This retunrs false because the second = is interpreted as a comparison. Then you are basically doing Set txtBx = False which causes the error.
It could also be that vba tries to assign the Text property which is a string to txtBx.
edit: I would also suggest using Option Explicit. If VBA knows that txtBx is supposed to be a shape, it tells you it got a type mismatch. In this case you got lucky because the Set tells it to expect an object and thus threw an error. If you wanted to assign a string for example, you would have gotten the error at a later line (or no error at all) because you have False where you expect a string which makes debugging more complicated.

Related

Data label Properties not being set for a chart in PPT

I am trying to set the data-label properties of a data point using this code snippet, but for some reason the properties are not being set as intended. [ Please see the pic for better clarity ].
A workaround could be using the Reset label Text [ See Pic - 2 ] thus forcing the data-label to update the set properties. But I couldn't find the vba equivalent of the same. Help.
'This is happening inside a loop
Dim thisbarpoint As Point
Set thisbarpoint = thischart.FullSeriesCollection(ibar).Points(jbar)
thisbarpoint.DataLabel.ShowCategoryName = True
thisbarpoint.DataLabel.ShowValue = False
thisbarpoint.DataLabel.ShowSeriesName = False
Debug.Print thisbarpoint.DataLabel.caption
Dim DataLabelCaption As String
DataLabelCaption = thisbarpoint.DataLabel.caption
Debug.Print DataLabelCaption 'This gives the value as 26.7%
PIC-1:
PIC-2:
This worked fine for me:
Dim cht As Chart, s As Series
Set cht = ActivePresentation.Slides(1).Shapes(1).Chart
Set s = cht.SeriesCollection(1)
Debug.Print s.HasDataLabels 'False
s.HasDataLabels = True
With s.DataLabels
.ShowCategoryName = True
.ShowValue = False
.ShowSeriesName = False
End With
We can't know if your file is corrupted, or if the problem is elsewhere in code you didn't include.

Excel VBA: Update a Charts X-Axis Min, Max, & Unit Values via click-button event

I would profoundly appreciate assistance from anyone regarding dynamically updating the X-Axis value of an Excel Bar-Chart via EITHER in-sheet formulae OR via VBA-code.
I've unsuccessfully tried the following:
---Created a named-range on the 3 in-sheet cells (Q2, R2, & S2) which will always contain the occassionally updated values for:
X-Axis-Minimum,
X-Axis-Maximum, and
X-Axis-Major-Units.
Then typed the following formula into each of the respective /Format.Axis/Axis.Options dialog-interface data-boxes for all of those 3 variables...:
=MAIN!XMIN
=MAIN!XMAX
=MAIN!XUNITS
...respectively, where "MAIN" is the name I've assigned to Sheet1.
However, the dialog-interface data-boxes do not retain the formulas, but simply revert back to whatever data was previously in there.
Alternatively, I've tried to solve this via VBA using the following algorithm variations tied to an ActiveX-Control button named "ReCalibrateButton".
Please help me determine which of the following algorithm iterations is most efficient and closest to accurate; as well as what's missing or wrong and preventing it from working successfully:
(Algorithm #1)
Private Sub ReCalibrateButton_Click()
Dim wsChart As Chart
Dim wsInput As Worksheet
Set wsChart = EAMPVPMSChart
Set wsInput = ThisWorkbook.Sheets("MAIN")
With wsChart
With .Axes(xlCategory)
.MinimumScale = wsInput.Range("Q2").Value
.MaximumScale = wsInput.Range("R2").Value
.MajorUnit = wsInput.Range("S2").Value
End With
End With
End Sub
When run, this algorithm unfortunately yields the following error= "Compile Error: Variable not defined"
What have i missed or done wrong within this algorithm?
(Algorithm #2)
Private Sub ReCalibrateButton_Click()
Dim objCht As ChartObject
For Each objCht In ActiveSheet.ChartObjects
With objCht.Chart
' Value (X) Axis
With .Axes(xlCategory)
.MinimumScale = ActiveSheet.Range("Q2").Value
.MaximumScale = ActiveSheet.Range("R2").Value
.MajorUnit = ActiveSheet.Range("S2").Value
End With
End With
Next objCht
End Sub
When run, this algorithm unfortunately yields the following
error= "Run-time error '-2147467259 (80004005)' Method 'MinimumScale' of object 'Axis' failed"
What have i missed or done wrong within this algorithm?
(Algorithm #3)
Private Sub ReCalibrateButton_Click()
Dim wsChart As Chart
Dim wsInput As Worksheet
Set wsChart = ThisWorksheet.Charts("EAMPVPMSChart")
Set wsInput = ThisWorkbook.Sheets("MAIN")
With wsChart
With .Axes(xlCategory)
.MinimumScale = wsInput.Range("Q2").Value
.MaximumScale = wsInput.Range("R2").Value
.MajorUnit = wsInput.Range("S2").Value
End With
End With
End Sub
When run, this algorithm unfortunately yields the following
error= "Compile Error: Variable not defined"
What have i missed or done wrong within this algorithm?
(Algorithm #4)
Private Sub ReCalibrateButton_Click()
Dim wksCharts As Worksheet
Dim oChrtObj As ChartObject
Set wksCharts = Worksheets("MAIN")
With wksCharts.ChartObjects("EAMPVPMSChart").Chart
oChrtObj.Chart.Axes(xlCategory).MinimumScale = ActiveSheet.Range("Q2").Value
oChrtObj.Chart.Axes(xlCategory).MaximumScale = ActiveSheet.Range("R2").Value
oChrtObj.Chart.Axes(xlCategory).MaximumScale = ActiveSheet.Range("S2").Value
End With
End Sub
When run, this algorithm unfortunately yields the following
error= "Run-time error '91': Object variable or With block variable not set"
What have i missed or done wrong within this algorithm?
(Algorithm #5)
Private Sub ReCalibrateButton_Click()
ActiveSheet.ChartObjects("EAMPVPMSChart").Activate
With Application.ActiveChart.Axes(xlCategory, xlPrimary)
.MinimumScale = wsInput.Range("Q2").Value
.MaximumScale = wsInput.Range("R2").Value
.MajorUnit = wsInput.Range("S2").Value
End With
End Sub
When run, this algorithm unfortunately yields the following
error= "Compile Error: Variable not defined"
What have i missed or done wrong within this algorithm?
public static void foryou(Microsoft.Office.Interop.Excel.Worksheet TheWorksheet)
{
double MyMajorUnit;
double MaxSelect = 10;
double MinSelect = 0;
foreach (Microsoft.Office.Interop.Excel.ChartObject TheChartObject in TheWorksheet.ChartObjects())
{
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorUnitIsAuto = false;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MaximumScaleIsAuto = false;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).HasMajorGridlines = true;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorGridlines.Format.Line.Visible = true;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorGridlines.Format.Line.Weight = 0.5;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorGridlines.Format.Line.Transparency = 0.5;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorGridlines.Format.Line.ForeColor.RGB = Color.FromArgb(160, 160, 160);
MyMajorUnit = (MaxSelect - MinSelect) / 6;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MajorUnit = MyMajorUnit;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MaximumScale = MaxSelect + MyMajorUnit;
TheChartObject.Chart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue).MinimumScale = MinSelect - MyMajorUnit;
}
}
-o-o-o-
Good Luck
Lucien

Formatting issue while exporting data to Excel using VBA macro

I am using below VBS code to export one chart (from QlikView) to excel.
Reason I am using Number format = ‘#’ and paste special because if I do not use it then values in the chart like ‘22001E-07’ gets converted to 2.20E-03
sub GPOTest1
set oXL=CreateObject("Excel.Application")
oXL.visible=True
oXL.Workbooks.Add
aSheetObj=Array("CH01")
for i=0 to UBound(aSheetObj)
oXL.Sheets.Add
Set oSH = oXL.ActiveSheet
oSH.Range("A1").Select
Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))
obj.CopyTableToClipboard True
oSH.Columns("B").NumberFormat = "#" ‘In “B” column I get values like 22001E-07
oSH.PasteSpecial -4163
sCaption=obj.GetCaption.Name.v
set obj=Nothing
oSH.Rows("1:1").Select
oXL.Selection.Font.Bold = True
oSH.Cells.Select
oXL.Selection.Columns.AutoFit
oSH.Range("A1").Select
oSH.Name=left(sCaption,30)
set oSH=Nothing
next
set oXL=Nothing
end sub
After running it for the first time, from 2nd time I get message
PasteSpecial method of Worksheet class failed
Referred following link, however, issue persists:
use macro to convert number format to text in Excel
You shouldn't systematically create an Excel instance. Your code leaves Excel open. Once Excel is open, the next time around, you can get a reference to it using GetObject. See the approach taken in the code below, where I've also simplified a couple things:
Sub GPOTest1()
On Error Resume Next
Set oXL = CreateObject("Excel.Application")
If oXL Is Nothing Then
Set oXL = GetObject(Class:="Excel.Application")
End If
On Error GoTo 0
oXL.Visible = True
Set oWB = oXL.Workbooks.Add
aSheetObj = Array("CH01")
For i = 0 To UBound(aSheetObj)
Set oSH = oWB.Sheets.Add
Set obj = ActiveDocument.GetSheetObject(aSheetObj(i))
obj.CopyTableToClipboard True
oSH.Columns("B").NumberFormat = "#" 'In “B” column I get values like 22001E-07
oSH.PasteSpecial -4163
oSH.Rows("1:1").Font.Bold = True
oSH.Columns.AutoFit
oSH.Range("A1").Select
oSH.Name = Left(obj.GetCaption.Name.v, 30)
Set oSH = Nothing
Set obj = Nothing
Next
Set oXL = Nothing
End Sub

VB Com Error for Naming Sheets on a Worksheet

I keep getting an error that says
"An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in
Microsoft.VisualBasic.dll"
Additional information: Exception from HRESULT: 0x800A03EC"
on the line where I'm trying to change the name of the sheets from Workbook reportApp. On my timeWorkbook there are headings in cells A1, then cell D1, and so on.
I want it to loop until there is no more values, but I can't change the name. I can change the name of the sheets in that workbook if I put reportApp.Sheets(s).Name = "Name this sheet", but I don't want to do that. I was wondering if there was any problem with my type or code that would get around this?
Private Sub generateReportButton_Click(sender As Object, e As EventArgs) Handles generateReportButton.Click
Dim timeApp As Excel.Application = New Excel.Application
Dim timeClockPath As String = "C:\Users\njryn_000\Desktop\Project ACC\Clock-In Excel\TimeClock.xlsx"
Dim timeWorkbook As Excel.Workbook = timeApp.Workbooks.Open(timeClockPath, ReadOnly:=False, IgnoreReadOnlyRecommended:=True, Editable:=True)
Dim timeWorksheet As Excel.Worksheet = timeWorkbook.Worksheets("TA")
Dim reportApp As Excel.Application = New Excel.Application
Dim reportPath As String = "C:\Users\njryn_000\Desktop\Project ACC\Report\Blank Timecard Report9.xlsx"
Dim reportWorkbook As Excel.Workbook = reportApp.Workbooks.Open(reportPath, ReadOnly:=False, IgnoreReadOnlyRecommended:=True, Editable:=True)
Dim reportWorksheet As Excel.Worksheet = reportWorkbook.Worksheets("Sheet" & 1)
Dim s As Integer
Dim i As Integer
Dim f As Integer
Dim taName As String
Dim taID As String
i = 0
f = 0
s = 1
With timeWorksheet.Range("A1")
Do
i += 3
s += 1
reportApp.Sheets(s).Name = timeWorksheet.Range("A1").Offset(0, i).Value
Loop Until IsNothing(timeWorksheet.Range("A1").Offset(0, 0).Offset(0, i).Value)
You've already solved your problem but you may not be able to add an answer yet so here is some feedback.
When you use a With block you can then refer to whatever you referenced at the top of that block with a single dot ('.') after that. Its a syntax which reduces writing the same thing over and over. In the snippet below I've removed all references to timeWorksheet.Range("A1") and added a leading dot.
With timeWorksheet.Range("A1")
Do
i += 3
s += 1
' Since you are using a With block this statement is simplified.
reportApp.Sheets(s).Name = .Offset(0, i).Value
' I removed the .Offset(0, 0) as it is redundant.
' If you have it in to solve a bug you can put it back.
Loop Until IsNothing(.Offset(0, i).Value)
' More code here...
End With
Also you've realised that you can use the Val() function to fix your code. Reading the documentation, it explains that this function will take a string and begin reading a number from it, ignoring whitespace. As soon as it reaches a non-numeric, non-whitespace character it stops and returns the number ignoring whatever else is in the string.
It seems that this isn't really solving your problem, it just works around it. I'd look at what other characters are present in the cells you are looping through and deal with them explicitly. Otherwise you might end up with strange results.

VB.net Object reference not set error

So I am getting this error Object Reference not set to an instance of an object. for some reason when I run it image = nothing which is causing rng = code to get this error.
Dim image As Excel.Shape
' This sets a reference to the image/end indactor.
image = oSheet.Shapes(oSheet.Shapes.Count)
' This sets up the range we are going to want to cut/copy over.
rng = oSheet.Range("A1", oSheet.Cells(image.TopLeftCell.Row + 3, 8))
You should always check for potential errors - especially when dealing with things like Excel!
Dim image As Excel.Shape
' This sets a reference to the image/end indactor.
image = oSheet.Shapes(oSheet.Shapes.Count)
If image IsNot Nothing Then
' This sets up the range we are going to want to cut/copy over.
rng = oSheet.Range("A1", oSheet.Cells(image.TopLeftCell.Row + 3, 8))
Else
Throw New Exception("There are no shapes on the sheet 'oSheet'.")
End If
That of course assumes oSheet is not Nothing as well. I hope that helps you on your way.