GTk printing 0ne p[age documents - gtk3

I have a problem printing one page documents in GTK 3.0.
Documents with more than one page are correctly printed but one page documents are not printed.
Because using the debugger in GNAT Studio 23.0w (20220512) is sometimes a problem I have printed some inbetween results during running to the GTK textview. I found that the program not even reaches Draw_Page from Connect_and_Run.
My question is what should I do to also correctly print one page documents.
The insert_at_buffer function (procedure) is used to print to the Text view and result of these statements are seen below
For your information On_Print the code is using:
Set_N_Pages (Print_Op, nr_Pages);
Set_Use_Full_Page(Print_Op, true);
Set_Unit (Print_Op, points);
--DEBUG-------------------------------------------------------------------
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Set_Unit (Print_Op, points)"), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("nr_Pages =") & Gint'image(nr_Pages) & " Filetype " & Windows'image(nb), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Ofirst_line =") & integer'image(first_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("last_line =") & integer'image(last_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("delta_lines =") & integer'image(delta_lines), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Number =") & long_float'image(Number), 0, true));
--------------------------------------------------------------------------
Print_Op.Set_Print_Settings(Print_Set);
-------------------------------------------------------------------
-- procedure On_Draw_Page
-- (Self : not null access Gtk_Print_Operation_Record;
-- Call : Cb_Gtk_Print_Operation_Gtk_Print_Context_Gint_Void;
-- After : Boolean := False);
--------------------------------------------------------------------
--DEBUG-------------------------------------------------------------------
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Print_Op.Set_Print_Settings(Print_Set)"), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("nr_Pages =") & Gint'image(nr_Pages) & " Filetype " & Windows'image(nb), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Ofirst_line =") & integer'image(first_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("last_line =") & integer'image(last_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("delta_lines =") & integer'image(delta_lines), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Number =") & long_float'image(Number), 0, true));
--------------------------------------------------------------------------
On_Draw_Page(Print_Op, Draw);
--DEBUG-------------------------------------------------------------------
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("On_Draw_Page(Print_Op, Draw)"), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("nr_Pages =") & Gint'image(nr_Pages) & " Filetype " & Windows'image(nb), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Ofirst_line =") & integer'image(first_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("last_line =") & integer'image(last_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("delta_lines =") & integer'image(delta_lines), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Number =") & long_float'image(Number), 0, true));
--------------------------------------------------------------------------
Result := Connect_and_Run(Print_Op ,Action_Print_Dialog, Main_Window);
-- --DEBUG-------------------------------------------------------------------
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Connect_and_Run(Print_Op ,Action_Print_Dialog, Main_Window)"), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("nr_Pages =") & Gint'image(nr_Pages) & " Filetype " & Windows'image(nb), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Ofirst_line =") & integer'image(first_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("last_line =") & integer'image(last_line), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("delta_lines =") & integer'image(delta_lines), 0, true));
Insert_At_Cursor(Text_Buffers(nb), buf_string(To_Unbounded_String("Number =") & long_float'image(Number), 0, true));
--------------------------------------------------------------------------
In Draw_Page also someinformation lines are presented:
nr := first_line;
Cr := Get_Cairo_Context (Context);
Set_Source_Rgb (Cr, 0.0, 0.0, 0.0);
Select_font_face(Cr, "Consolas", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
Set_Font_Size(Cr, GDouble(10));
if nr = 1 then
pagenr := 1;
else
pagenr := pagenr + 1;
end if;
if pagenr rem 2 = 1 then
width := 70;
else
width := 40;
end if;
if last_page_line > last_line then
last_page_line := last_line;
end if;
len := 3;
nr1 := 10;
while last_line > nr1 - 1 loop
nr1 := nr1 * 10;
len := len + 1;
end loop;
--DEBUG-------------------------------------------------------------------
Insert_At_Cursor(Text_Buffers(Window_Type), buf_string(To_Unbounded_String("Draw_Page "), 0, true));
Insert_At_Cursor(Text_Buffers(Window_Type), buf_string(To_Unbounded_String("pagenr = ") & integer'image(pagenr), 0, true));
Insert_At_Cursor(Text_Buffers(Window_Type), buf_string(To_Unbounded_String("first_line = " & integer'image(first_line) & " Buffer = " & Windows'image(Window_Type)), 0, true));
Insert_At_Cursor(Text_Buffers(Window_Type), buf_string(To_Unbounded_String("last_line = ") & integer'image(last_line), 0, true));
Insert_At_Cursor(Text_Buffers(Window_Type), buf_string(To_Unbounded_String("last_page_line = ") & integer'image(last_page_line), 0, true));
--------------------------------------------------------------------------
>With a one page document I got:
>Set_Unit (Print_Op, points)
>nr_Pages = 1 Filetype GL
>first_line = 1
>last_line = 15
>delta_lines = 56
>Number = 1.00000000000000E+00
>Print_Op.Set_Print_Settings(Print_Set)
>nr_Pages = 1 Filetype GL
>first_line = 1
>last_line = 15
>delta_lines = 56
>Number = 1.00000000000000E+00
>On_Draw_Page(Print_Op, Draw)
>nr_Pages = 1 Filetype GL
>first_line = 1
>last_line = 15
>delta_lines = 56
>Number = 1.00000000000000E+00
>Connect_and_Run(Print_Op ,Action_Print_Dialog, Main_Window)
>nr_Pages = 1 Filetype GL
>first_line = 1
>last_line = 15
>delta_lines = 56
>Number = 1.00000000000000E+00
>With a Multipage document I got:
>Set_Unit (Print_Op, points)
>nr_Pages = 2 Filetype BI
>first_line = 1
>last_line = 68
>delta_lines = 56
>Number = 2.00000000000000E+00
>Print_Op.Set_Print_Settings(Print_Set)
>nr_Pages = 2 Filetype BI
>first_line = 1
>last_line = 68
>delta_lines = 56
>Number = 2.00000000000000E+00
>On_Draw_Page(Print_Op, Draw)
>nr_Pages = 2 Filetype BI
>first_line = 1
>last_line = 68
>delta_lines = 56
>Number = 2.00000000000000E+00
>Draw_Page
>pagenr = 1
>first_line = 1 Buffer = BI
>last_line = 68
>last_page_line = 57
>Draw_Page
>pagenr = 2
>first_line = 58 Buffer = BI
>last_line = 68
>last_page_line = 68
>Connect_and_Run(Print_Op ,Action_Print_Dialog, Main_Window)
>nr_Pages = 2 Filetype BI
>first_line = 69
>last_line = 68
>delta_lines = 56
>Number = 2.00000000000000E+00

I Solved the problem.It was a problem caused by the arrangement of variuos statements creating Print_Op and Print_Set. I just tried variuos arrangements and all of a sudden the program worked

Related

Cannot get my chart ‘stacked’ using a Calc macro

Somehow I cannot get my chart to ‘stack’. For reasons explained below I first prepare a standard chart in a macro called ‘ChartsGeneral’. Based on some settings on my ‘Charts’ worksheet, it then calls a specific second macro, e.g. ‘ChartBuildStatus’. In this second macro I generate the category and data-series, and adjust the settings of the standard chart as necessary.
When I try to get a stacked chart via ‘createInstance(“com.sun.star.chart.StackableDiagram”)’ nothing changes. I have studied the documentation and several forums, but I have no clue what I am missing. Code below.
Configuration details
Version: 7.4.3.2 (x64) / LibreOffice Community
CPU threads: 12; OS: Windows 10.0 Build 19045; Locale: nl-NL (nl_NL); UI: en-US
OK, here it goes… Please have some mercy on a poor old non-programmer nerd.
Background
Over the years I collected a rather large set of Excel spreadsheets with VBA macros for my personal finances. This year I decided to migrate them all to LibreOffice, as part of my wider migration from Windows to Linux. I am not a programmer, so I decided to use BASIC as it would be closest to VBA.
One of my spreadsheets tracks progress on our home mortgage. I keep track of all payments on interest and principal. As we are paying down extra with a fixed monthly payment and a ‘snowball’ (all savings go back as payments to the principal) the spreadsheet also calculates the expected next snowball payment, as well as a prognosis for the remainder of the mortgage. That all works fine.
The key worksheets in my Mortgage spreadsheet are ‘Months’, where I store all the data of past payments, and ‘Prognosis’, which holds a copy of ‘Months’ but also a prognosis for every month in the future.
I am now down to the last block of functionality: reporting. This is mainly a collection of charts that show the history, current status and prognosis for my mortgage based on the data in Months and Prognosis. For this I use a dedicated worksheet called ‘Charts’ in my spreadsheet. Here I can select a Chart Type from a dropdown-list, as well as some date or period related settings (I use named fields for this). See a partial screenshot below.
Partial Screenshot of Charts worksheet
When I press the ‘Update Chart’ button on my Charts worksheet, a macro called ‘ChartsGeneral’ is triggered. In this macro:
I use the date or period related settings to calculate the starting row and ending row for the data series
I then generate an empty standard linechart called ‘AdminChart’ on the Charts worksheet, with settings for the axes, the formatting, and everything
I call a second macro based on the ChartType value on Charts. In the above example the chart is called ‘Opbouw Stand van Zaken’, so I call a second macro called ChartBuildStatus.
The code for ChartsGeneral can be found below
Sub ChartsGeneral()
'Manages the Charts worksheet
'Set Worksheets
wshC = ThisComponent.Sheets.getByName("Charts")
wshM = ThisComponent.Sheets.getByName("Months")
wshP = ThisComponent.Sheets.getByName("Prognosis")
wshS = ThisComponent.Sheets.getByName("Settings")
'Define Colours
cBlack = RGB(0, 0, 0)
cGray01 = RGB(50, 50, 50)
cGray02 = RGB(191, 191, 191)
cWhite = RGB(255, 255, 255)
cDarkRed = RGB(192, 0, 0)
cPinkiDEAL = RGB(204, 0, 102) 'iDeal
cGreenCash = RGB(112, 173, 71) 'Cash Green
cBluePin = RGB(41, 65, 113) 'PIN Blue
cBlueContactless = RGB(58, 125, 193) 'Contactloos Light Blue
cOrangeVisa = RGB(246, 155, 14) 'Visa Orange
'Set Parameters
'Prognosis
ColumnOriginal = 18 'Original Rest Mortgage
ColumnRest = 17 'Actual Rest Mortgae
ColumnPaid = 16 'Reeds afgelost
ColumnPrognosis = 21 'Prognosis Rest Mortgage
ColumnInterestSavedPrognosis = 23 'Bespaarde rente prognose
ColumnInterestSaved = 26 'Bespaarde rente
ColumnExtraTotal = 14 'Column total extra cumulative
ColumnPercent = 24
ColumnPercentPrognosis = 25
'Months
XASColumn = 2
ColumnExtra = 13 'Extra repayment column
ColumnRegular = 12 'Regular repayment column
ColumnInterest = 11 'Interest payment column
ColumnMonthInterest = 3 'Interest payment column
ColumnMonthRegular = 4 'Regular repayment column
ColumnMonthTotal = 9 'Total Monthly repayment column
ColumnSnowball = 7 'Snowball per month column
ColumnWOZ = 17 'WOZ column
ColumnMortgage = 16 'Rest of mortgage column
ColumnVasteLasten = 5 'Regular Interest and Depreciation
ColumnLTV = 21 'LTV Ratio
ColumnPercentageRest = 24 'Percentage Rest Mortgage Paid This Month
ColumnWOZpercentage = 22 'WOZ percentage column
ColumnMortgagePercentage = 26 'Rest of mortgage percentage column
'X-As Values
LastMonthRow = getLastContentIndex("Months", 3)
If wshM.getCellByPosition(1, LastMonthRow).Value = (ThisComponent.NamedRanges.getByName("ChartMonth").getReferredCells.Value + 1) Then
LastMonthRow = LastMonthRow - 1
End If
LastMonth = wshM.getCellByPosition(1, LastMonthRow).Value
LastYear = wshM.getCellByPosition(0, LastMonthRow).Value
xStartRow = 3
xEndRow = LastMonthRow
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "1Y" Then
StartYear = LastYear - 1
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "2Y" Then
StartYear = LastYear - 2
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "3Y" Then
StartYear = LastYear - 3
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "5Y" Then
StartYear = LastYear - 5
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "10Y" Then
StartYear = LastYear - 10
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "15Y" Then
StartYear = LastYear - 15
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "20Y" Then
StartYear = LastYear - 20
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
'Global Variable for BlogMarkers
ChartStartRow = StartRow
'Generate New Chart
oCharts = wshC.Charts
If oCharts.Count <> 0 then
For i = 0 to oCharts.Count-1
oChart = oCharts.getByIndex(i)
If oChart.name = "AdminChart" then
oCharts.removeByName("AdminChart")
End If
Next i
End If
Dim oRange as Object
Dim oRangeAddress(1) As New com.sun.star.table.CellRangeAddress
Dim oRect As New com.sun.star.awt.Rectangle
Dim cTitle as String
'Define Point and Size in order to change Position and Size of Chart Objects
Dim Pos_Chart As New com.sun.star.awt.Point
Dim Pos_Title As New com.sun.star.awt.Point
Dim Pos_SubTitle As New com.sun.star.awt.Point
Dim Pos_xTitle As New com.sun.star.awt.Point
Dim Pos_yTitle As New com.sun.star.awt.Point
Dim Pos_Legend As New com.sun.star.awt.Point
Dim Size_Chart As New com.sun.star.awt.Size
Dim Size_Title As New com.sun.star.awt.Size
Dim Size_SubTitle As New com.sun.star.awt.Size
Dim Size_xTitle As New com.sun.star.awt.Size
Dim Size_yTitle As New com.sun.star.awt.Size
Dim Size_Legend As New com.sun.star.awt.Size
oRange = thisComponent.getCurrentSelection.getRangeAddress
oRect.Width = 34000
oRect.Height = 19500
oRect.X = 8650
oRect.Y = 20
cTitle = "AdminChart"
oCharts.addNewByName(cTitle,oRect,oRangeAddress(), TRUE, TRUE)
oChart = oCharts.getByName(cTitle).embeddedObject
oChart.Diagram = oChart.createInstance("com.sun.star.chart.LineDiagram") 'LineDiagram
oDiagram = oChart.Diagram
'Change position and size of chart area in rectangle
oChart.RefreshAddInAllowed = True
Pos_Chart.X = 700
Pos_Chart.Y = 1600
Size_Chart.Width = oRect.Width - 1500
Size_Chart.Height = oRect.Height - 2500
oDiagram.setPosition( Pos_Chart )
oDiagram.setSize( Size_Chart )
'Title and Subtitle of Chart
'oChart.SplineType = 0
oChart.HasMainTitle = True
oChart.Title.String = cTitle
oChart.Title.CharColor = cBlack
oChart.Title.CharFontName = "Liberation Sans"
oChart.Title.CharHeight = 16 ' Font Size
oChart.Title.CharWeight = 0 ' Bold in %
oChart.Title.CharPosture = 0 ' Italics = 1
oChart.HasSubTitle = False
'oChart.SubTitle.String = "Testing the waters"
'oChart.SubTitle.CharColor = cBlue
'oChart.SubTitle.CharFontName = "Liberation Sans"
'oChart.SubTitle.CharHeight = 12 ' Font Size
'oChart.SubTitle.CharWeight = 100 ' Bold in %
'oChart.SubTitle.CharPosture = 0 ' Italics
'Chart Area colours
oDiagram.Wall.FillStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.Wall.FillColor = cWhite 'Chart Area Colour
oDiagram.Wall.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.Wall.LineColor = cBlack 'Chart Area Border Colour
oDiagram.Wall.LineWidth = 20
oChart.Area.FillStyle = com.sun.star.drawing.FillStyle.SOLID
oChart.Area.FillColor = cWhite 'Full Area Colour
'Horizontal Major Grid Lines
oDiagram.HasYAxisGrid = True
oDiagram.YMainGrid.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.YMainGrid.LineColor = cGray02
oDiagram.YMainGrid.LineWidth = 20
'Vertical Major Grid Lines
oDiagram.HasXAxisGrid = False
oDiagram.XMainGrid.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.XMainGrid.LineColor = cGray02
oDiagram.XMainGrid.LineWidth = 20
'X-Axis
oDiagram.HasXAxis = True
oDiagram.HasXAxisDescription = True
oDiagram.HasXAxisTitle = True
oXaxis = oDiagram.getXAxis()
oXaxis.AxisTitle.String = "X-Values"
oXaxis.AxisTitle.CharFontName = "Liberation Sans"
oXaxis.AxisTitle.CharColor = cBlack
oXaxis.AxisTitle.CharHeight = 11 ' Font Size
oXaxis.AxisTitle.CharWeight = 0 ' Bold in %
oXaxis.AxisTitle.CharPosture = 0 ' Italics = 1
oXaxis.AutoMin = True
oXaxis.AutoMax = True
'oXaxis.Min = 1
'oXaxis.Max = 5
oXaxis.CharColor = cBlack
oXaxis.CharFontName = "Liberation Sans"
oXaxis.CharHeight = 10 ' Font Size
oXaxis.CharWeight = 100 ' Bold in %
oXaxis.CharPosture = 0 ' Italics
oXaxis.LineColor = cBlack
oXaxis.LineWidth = 20
'Primary Y-Axis
oDiagram.HasYAxis = True
oDiagram.HasYAxisDescription = True
oDiagram.HasYAxisTitle = False
oDiagram.HasYAxis = True
oYaxis = oDiagram.getYAxis()
oYaxis.AxisTitle.String = "Y-Values"
oYaxis.AxisTitle.CharFontName = "Liberation Sans"
oYaxis.AxisTitle.CharColor = cBlack
oYaxis.AxisTitle.CharHeight = 11 ' Font Size
oYaxis.AxisTitle.CharWeight = 0 ' Bold in %
oYaxis.AxisTitle.CharPosture = 0 ' Italics = 1
oYaxis.AutoMin = False
oYaxis.AutoMax = False
oYaxis.Min = 0
oYaxis.Max = 2000
oYaxis.StepMain = 250
oYaxis.CharColor = cBlack
oYaxis.CharFontName = "Liberation Sans"
oYaxis.CharHeight = 10 ' Font Size
oYaxis.CharWeight = 0 ' Bold in %
oYaxis.CharPosture = 0 ' Italics
oYaxis.LineColor = cBlack
oYaxis.LineWidth = 20
oYaxis.LinkNumberFormatToSource = False
oYaxis.NumberFormat = "114"
oChart.HasLegend = 1
oLegend = oChart.getLegend()
oLegend.AutomaticPosition = True
oLegend.Alignment = com.sun.star.chart.ChartLegendPosition.BOTTOM
oLegend.CharHeight = 10 ' Font Size
oLegend.CharWeight = 0 ' Bold in %
oLegend.CharFontName = "Liberation Sans"
oLegend.FillColor = cWhite
oLegend.LineColor = cWhite
oLegend.CharColor = cBlack
oLegend.CharPosture = 0 'Italics
oDiagram.Lines = True
oDiagram.LineColor = cDarkRed
oDiagram.LineWidth = 20
'oChart.DataSourceLabelsInFirstColumn = True
'oChart.DataSourceLabelsInFirstRow = False
'Call Chart Procedure
If ThisComponent.NamedRanges.getByName("ChartType").getReferredCells.String = "Opbouw Stand van Zaken" Then
cTitle = "Opbouw Eigen Woning " & ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String
Call ChartBuildStatus(xStartRow, xEndRow, cTitle)
End If
End Sub
Once the macro ChartBuildStatus is called, that macro contains the following actions:
I change the chart type of AdminChart to AreaDiagram. That shows up correctly on my screen.
I then try to make it a stacked diagram. But it won’t…
After that, I change some formatting characteristics of the chart, like axis titles and number formats
And I generate the category and data series calling on two other macro’s, CreateDataSequence() and CreateDataSeries_Chart(). I don’think they are the problem, they work correctly with other non-stacked line charts and the series
I have tried a number of things, including moving the stacking code to the end of the macro. But I cannot get it to work correctly. I must be overlooking something or doing something very stupid. So after literally days of trying I am pinning my hopes on the community. Anybody who can shed some light on this?
Sub ChartBuildStatus(xStartRow As Long, xEndRow As Long, cTitle As String)
'Define Colours
cBlack = RGB(0, 0, 0)
cGray01 = RGB(50, 50, 50)
cGray02 = RGB(191, 191, 191)
cWhite = RGB(255, 255, 255)
wshC = ThisComponent.Sheets.getByName("Charts")
wshM = ThisComponent.Sheets.getByName("Months")
oCharts = wshC.Charts
oChart = oCharts.getByName("AdminChart").embeddedObject
oChart.Diagram = oChart.createInstance("com.sun.star.chart.AreaDiagram")
'Stackable Diagram
oChart.Diagram = oChart.createInstance("com.sun.star.chart.StackableDiagram")
oDiagram = oChart.getDiagram()
oChart.setDiagram(oDiagram)
oDiagram = oChart.getDiagram()
With oDiagram
.Stacked = True
.Percent = False
.Vertical = False
End With
ChartUnit = 50000
'Specific Chart Adjustments
oXaxis = oDiagram.getXAxis()
oYaxis = oDiagram.getYAxis()
'Ymax And Ymin
oYaxis.AutoMax = True
oYaxis.Min = 0
'Chart details
oChart.Title.String = cTitle
oDiagram.HasXAxisTitle = False
oYaxis.AxisTitle.String = "EUR"
oYaxis.StepMain = ChartUnit
oYaxis.NumberFormat = "115" ' #,##0
'Data Series Generator
oDataProvider = oChart.getDataProvider()
oDiagram = oChart.getFirstDiagram()
oCooSys = oDiagram.getCoordinateSystems()
oCoods = oCooSys(0) ' this chart has only a coordinate system
oChartTypes = oCoods.getChartTypes() ' chart type one by one
oChartType = oChartTypes(0)
'Data Ranges
xEndRow = getLastContentIndex ("Months", 3 )
Xrange = "Months.C" & (xStartRow + 1) & ":C" & (xEndRow + 1) 'yyyymm
Y1range = "Months.S" & (xStartRow + 1) & ":S" & (xEndRow + 1) 'Overwaarde
Y2range = "Months.T" & (xStartRow + 1) & ":T" & (xEndRow + 1) 'Eigen Geld
Y3range = "Months.M" & (xStartRow + 1) & ":M" & (xEndRow + 1) 'Reguliere Aflossing
Y4range = "Months.N" & (xStartRow + 1) & ":N" & (xEndRow + 1) 'Extra Aflossing
Y5range = "Months.Q" & (xStartRow + 1) & ":Q" & (xEndRow + 1) 'Restant Hypotheek
'Prepare for Data Series
oDataProvider = oChart.getDataProvider()
oDiagram = oChart.getFirstDiagram()
oCooSys = oDiagram.getCoordinateSystems()
oCoods = oCooSys(0) ' this chart has only a coordinate system
oChartTypes = oCoods.getChartTypes() ' chart type one by one
oChartType = oChartTypes(0)
'X-Axis Data series
dim categorySequence as object, categoryRange as string
dim coordinateSystem as object, axis as object
dim scaleData as new com.sun.star.chart2.ScaleData
categorySequence = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
categorySequence.setValues(CreateDataSequence(oDataProvider, Xrange, "categories"))
coordinateSystem = oDiagram.getCoordinateSystems()(0)
axis = coordinateSystem.getAxisByDimension(0, 0)
scaleData = axis.getScaleData()
scaleData.Categories = categorySequence
axis.setScaleData(scaleData)
'Y-Axis Data series
oDataSeriesList = oChartType.getDataSeries()
Dim oNewDataSeriesList(4) As Object ' new data series
oSeries1 = CreateDataSeries_Chart(oDataProvider, Xrange, Y1range, "Overwaarde")
oSeries1.Color = RGB(197, 224, 180)
oSeries1.LineWidth = 60
oNewDataSeriesList(0) = oSeries1
oSeries2 = CreateDataSeries_Chart(oDataProvider, Xrange, Y2range, "EigenGeld")
oSeries2.Color = RGB(0, 176, 80)
oSeries2.LineWidth = 60
oNewDataSeriesList(1) = oSeries2
oSeries3 = CreateDataSeries_Chart(oDataProvider, Xrange, Y3range, "Aflossing")
oSeries3.Color = RGB(146, 208, 80)
oSeries3.LineWidth = 60
oNewDataSeriesList(2) = oSeries3
oSeries4 = CreateDataSeries_Chart(oDataProvider, Xrange, Y4range, "AflossingExtra")
oSeries4.Color = RGB(255, 215, 0)
oSeries4.LineWidth = 60
oNewDataSeriesList(3) = oSeries4
oSeries5 = CreateDataSeries_Chart(oDataProvider, Xrange, Y5range, "RestHypotheek")
oSeries5.Color = RGB(192, 0, 0)
oSeries5.LineWidth = 60
oNewDataSeriesList(4) = oSeries5
'Update chart (only the charttype is updated)
oChartType.setDataSeries(oNewDataSeriesList)
End Sub
On the left the chart as it looks now in my LibreOffice Calc spreadsheet, on the right the chart as I want it to look based on my current Excel sheet.
Left: LibreOffice / Right: Excel (how I want it)
For the sake of completeness, please find the additional macro’s CreateDataSequence() and CreateDataSeries_Chart() below.
CreateDataSequence()
Function CreateDataSequence( oDataProvider As Object, sRangeRepresentation As String, sRole As String ) As Object
Dim oDataSequence As Object
On Error GoTo Handler
' create .chart2.data.DataSequence from range representation
oDataSequence = oDataProvider.createDataSequenceByRangeRepresentation(sRangeRepresentation)
If NOT IsNull(oDataSequence) Then
oDataSequence.Role = sRole
End If
Handler:
CreateDataSequence = oDataSequence
End Function
CreateDataSeries_Chart()
Function CreateDataSeries_Chart( oDataProvider As Object, sXRangeRepresentation As String, sYRangeRepresentation As String, sLabelRangeRepresentation As String ) As Object
Dim oNewDataSeries As Object
oNewDataSeries = CreateUnoService("com.sun.star.chart2.DataSeries")
Dim oData(1) As Object ' x and y: .chart2.data.XLabeledDataSequence
' Y
oDataY = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
oSequenceY = CreateDataSequence(oDataProvider, sYRangeRepresentation, "values-y")
If NOT IsNull(oSequenceY) Then
oDataY.setValues(oSequenceY)
If NOT ((IsMissing(sLabelRangeRepresentation)) AND (sLabelRangeRepresentation <> "")) Then
oSequenceLabel = CreateDataSequence(oDataProvider, sLabelRangeRepresentation, "label") ' ""
oDataY.setLabel(oSequenceLabel) ' oSequenceLabel label is used as name
End If
End If
' X
oDataX = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
oSequenceX = CreateDataSequence(oDataProvider, sXRangeRepresentation, "values-x")
If NOT IsNull(oSequenceX) Then
oDataX.setValues(oSequenceX)
End If
' set x and y data to series
aData = Array(oDataY, oDataX)
oNewDataSeries.setData(aData)
CreateDataSeries_Chart = oNewDataSeries
End Function

Why is TIC-80 giving me the attempt to index a nil value error?

So I am building a game for a game jam over at itch.io, and I'm using this really neat Fantasy Console called TIC-80, found at tic80.com. My issue is that while I understand what the error message is and what it means, I don't understand as to why it's giving me this error.
Error Message (In the TIC-80 console):
>[string "-- title: The Clone
Wars..."]:144: attempt to index a nil
value (field '?')
stack traceback:
[string "-- title: The Clone
Wars..."]:144: in function 'TIC'
The Code in question:
-- title: The Clone Wars
-- author: DinoNuggies
-- desc: Help the jedi destroy the clones!
-- script: lua
--Functions
function sign(n) return n>0 and 1 or n<0 and -1 or 0 end
function lerp(a,b,t) return (1-t)*a + t*b end
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
--End of Functions
--Variables
player = {
spr = 256,
sprMod = 0,
x = 1,
y = 1,
vx = 0,
vy = 0,
dirX = 0,
dirY = 0,
flip = 0,
shoot = false,
}
gun = {
t = 0,
spr = 258,
sprMod = 0,
x = 0,
y = 0,
modX = 0,
modY = 0,
flip = 0,
rot = 0,
}
tile = {
r0 = 0,
r1 = 0,
l0 = 0,
l1 = 0,
u0 = 0,
u1 = 0,
d0 = 0,
d1 = 0,
m = 0,
}
m = {
x = 0,
y = 0,
left = false,
right = false,
middle = false,
}
cam = {
activate = true,
x = 120,
y = 64,
}
--Bullet Class & Functions
bulletMod = 0
bullet = {}
function bullet:new()
local this = {
spr = 260,
x = player.x,
y = player.y,
vx = 0,
vy = 0,
mx = m.x - (player.x + cam.x),
my = m.y - (player.y + cam.y),
t = 0,
}
return this
end
function bullet:remove()
local this = {
spr = nil,
x = nil,
y = nil,
vx = nil,
vy = nil,
mx = nil,
my = nil,
t = nil,
}
return this
end
--End of Variables
function TIC()
cls()
--Camera
if cam.activate then
cam.x = math.min(120, lerp(cam.x, 120-player.x, 0.05))
cam.y = math.min(64, lerp(cam.y, 64-player.y, 0.05))
ccx = cam.x / 8 + (cam.x % 8 == 0 and 1 or 0)
ccy = cam.y / 8 + (cam.y % 8 == 0 and 1 or 0)
end
map(15 - ccx, 8 - ccy, 31, 18, (cam.x % 8) - 8, (cam.y % 8) - 8, 0)
--End of Camera
--Gun Physics
m.x, m.y, m.left, m.middle, m.right = mouse()
gun.x = player.x + cam.x
gun.y = player.y + cam.y
bullets = tablelength(bullet) - 2
flick = (time() // 16) % 16 == 0
if m.left then m.leftp = flick else m.leftp = false end
--Gun Display
if m.x > player.x + cam.x + 4 then
gun.flip = 0
gun.modX = 4
else
gun.flip = 1
gun.modX = -4
end
--Gun Firing
if m.leftp == true then
bullet[bullets] = bullet:new()
if m.x > player.x + cam.x + 4 then
bullet[bullets].vx = 8
else
bullet[bullets].vx = -8
end
end
--End of Gun Physics
--Bullet Physics
if bullets > 0 then
for i=0,bullets-1 do
bullet[i].x = bullet[i].x + bullet[i].vx --LINE 144, THE ONE IN QUESTION
bullet[i].y = bullet[i].y + bullet[i].vy
spr(bullet[i].spr, bullet[i].x + cam.x, bullet[i].y + cam.y, 0, 1)
bullet[i].t = bullet[i].t + 1
if bullet[i].t > 16 then
bullet[i] = bullet:remove()
bullet[i] = nil
end
end
end
bullets = tablelength(bullet) - 2
--End of Bullet Physics
--Drawing
--Sprites
spr(player.spr + player.sprMod, player.x + cam.x, player.y + cam.y, 0, 1, player.flip)
spr(gun.spr + gun.sprMod, gun.x + gun.modX, gun.y + gun.modY, 0, 1, gun.flip, gun.rot)
--Debug
print("Debug:", 1, 1, 11)
print("X: " .. (player.x // 8) + 15 .. " Y: " .. (player.y // 8) + 9, 1, 8, 11)
print("BLTs: " .. bullets .. " ", 1, 16, 11)
--End of Drawing
--Player Movement
player.x = player.x + player.vx
player.y = player.y + player.vy
if key(1) and player.x > -120 then
player.vx = -1
player.sprMod = 1
player.dirX = 0
elseif key(4) then
player.vx = 1
player.sprMod = 0
player.dirX = 1
else
player.vx = 0
end
if key(23) and player.y > -64 then
player.vy = -1
player.dirY = 0
elseif key(19) then
player.vy = 1
player.dirY = 1
else
player.vy = 0
end
if btnp(0) then player.y = player.y - 1
elseif btnp(1) then player.y = player.y + 1
elseif btnp(2) then player.x = player.x - 1
elseif btnp(3) then player.x = player.x + 1
end
--End of Movement
--Player Collision
tile.r0 = mget(((player.x + 7) // 8) + 15, ((player.y - 9) // 8) + 9)
tile.r1 = mget(((player.x + 7) // 8) + 15, ((player.y - 2) // 8) + 9)
tile.l0 = mget(((player.x - 2) // 8) + 15, ((player.y - 9) // 8) + 9)
tile.l1 = mget(((player.x - 2) // 8) + 15, ((player.y - 2) // 8) + 9)
tile.u0 = mget(((player.x - 1) // 8) + 15, ((player.y - 10) // 8) + 9)
tile.u1 = mget(((player.x + 6) // 8) + 15, ((player.y - 10) // 8) + 9)
tile.d0 = mget(((player.x - 1) // 8) + 15, ((player.y - 1) // 8) + 9)
tile.d1 = mget(((player.x + 6) // 8) + 15, ((player.y - 1) // 8) + 9)
if player.dirX == 1 then
if fget(tile.r0, 0) or fget(tile.r1, 0) then
player.vx = 0
end
elseif player.dirX == 0 then
if fget(tile.l0, 0) or fget(tile.l1, 0) then
player.vx = 0
end
end
if player.dirY == 0 then
if fget(tile.u0, 0) or fget(tile.u1, 0) then
player.vy = 0
end
elseif player.dirY == 1 then
if fget(tile.d0, 0) or fget(tile.d1, 0) then
player.vy = 0
end
end
--End of Player Collision
--Misc
if keyp(3) then
if cam.activate then
cam.activate = false
else
cam.activate = true
end
end
--End of Misc
end
--DON'T WORRY ABOUT ANYTHING PAST THIS POINT, IT'S ONLY SPRITE AND TILE DEFINITIONS FOR TIC-80 VISUALS
-- <TILES>
-- 000:6666666666666666666666666666666666666666666666666666666666666666
-- 001:6666666666566566666666656666666665665666666665666566666666666666
-- 002:6668666666898566666866656666666665665866686689868986686668666666
-- 003:6656556666555556555556555555556555555555665555556556555666655566
-- 016:dddddddeddddddefddeeeeffddeeeeffddeeeeffddeeeeffdeffffffefffffff
-- 017:6226622661266126222222221121112161266126612661265126512665266525
-- 018:6228622661298126222222221121112161266126612681268126512668266525
-- 019:6226522661255126222222221121112151255125612551255126512665255525
-- </TILES>
-- <SPRITES>
-- 000:00cccc000cccccd00cbbbbb0ccbbcbbdcccfefcd0dddddd000ceec0000c00c00
-- 001:00cccc000cccccd00bbbbbd0cbbcbbcdccfefccd0dddddd000ceec0000c00c00
-- 002:000000000000000000000000000eeeed000efff0000ef0000000000000000000
-- 003:0000ed00000eef0000eef0000eef000000eef000000ee0000000000000000000
-- 004:0000000000000000000000000aaaaaa00aaaaaa0000000000000000000000000
-- </SPRITES>
-- <MAP>
-- 000:010101010101010101010101010101010101010101010101010101010101010000000000000000000000101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 001:010000000000000000000000000000101000101000001000000010101001010000000000100000000000101010000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 002:010001000100010000000000000010000000100010001000100010001001010000000010100000000000101010000000000000001010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 003:010001000100000000000000000000101000100010001000100010100001010000000010000000000000101000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 004:010001010100010000000000000000001000100010001000100010000001010000000010000000000000101010000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 005:010001000100010000000000000010100000001010000010100010000001010000000010000000000000101010000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 006:010000000000000000000000000101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 007:010000000000000000000000000101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 008:010000000000000000000000000101301010000000000000000000000000000000000000101010000000101000000000000000000010101000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 009:010000000000000000000000000101101010100000000000000000000000000000001010101000000000101000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 010:010000000000000000000000000101101010000000000001111101000000001111111121211111110000101000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 011:010000000000000000000000000101000000000000001000000001000000000000001020101000000000101000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 012:010000000000000000000000000101000000000000011111111101010001010000101010000000000010101000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 013:010000000000000000000000000101000000000010101000000001011101010000101000000000000010100000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 014:010000000000000000000000000101000000000010101010000000000000010000000000000000000010100000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 015:010000000000000000000000000101000000000000000000000000000000010000000000000000001010000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 016:010101010101010101010101010101000000000000000000000000000000010000000000000000001010000000000000001010000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 017:010101010101010101010101010101000000000000000000000000000000000000000000000000101010000000000010102000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- 018:000000000000000000000000000101000000000000000000000010100000000000000000000000101000000000001010000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 019:000000000000000000001010000101000000000000000000000000100000000000000000000010101000001111211110000000001010000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 020:000000001000000000001000000101000000000000000000000000101000000000000000001010101000000010101011111100000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 021:000000000000000000001010100101101010000000000000000000000000000000000000101000000000001010200000000011110000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 022:000000000000000000000000000101001010100000000000000000000000000000000010101000000010101010100000000000001111000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 023:000000000000000000000000000101000000000000000000000000000000000000001010100000000010101010000000000000000000110000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 024:000000000000000000000000000101000000000000000000000000000000000000001010100000001020201000000000000000100000001100102001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 025:000000000000000000000000000101000000000000000000000000000000000000101010000000001020100000000000000000100000000011212101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 026:000000101000000000000000000101000000000000000000000000000000001010100010000000001010100000000010000000100010100010101001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 027:000000101010000000000000100101000000000000000010101010101010101010000010000000001010000000000000101010000000001010000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 028:000000100010000000000000100101000000000000000000000000001010101000101010000000001010000010101010000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 029:000000001010000000000000000101000000000000000000000000000010100000000000000000001010000000000000000000100010000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 030:000000001010000000000000000101100000000000000000000000000000000000000000000000001000000000001000000000100000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 031:000000001010000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 032:000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 033:000000000000000000000000000101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- 135:010101010101010101010101010101010101010101010101010101010101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
-- </MAP>
-- <WAVES>
-- 000:00000000ffffffff00000000ffffffff
-- 001:0123456789abcdeffedcba9876543210
-- 002:0123456789abcdef0123456789abcdef
-- </WAVES>
-- <SFX>
-- 000:020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200304000000000
-- 001:020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200307000000000
-- 002:02000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020002000200020030b000000000
-- </SFX>
-- <FLAGS>
-- 000:00000000000000000000000000000000101010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-- </FLAGS>
-- <PALETTE>
-- 000:1a1c2c5d2810814428ca9581ffcd7575ae442495482571793c55c22c9dfae20000000000f4f4f494b0c2566c86333c57
-- </PALETTE>
What triggers the error, is after the player fires the second bullet. After firing one, the bullet is created, displayed, and despawned on queue, but after the second bullet starts existing, it stops and gives me the error. I've switched things around quite a bit, and it seems like every time I reference to one of the bullet objects values when more then one exists, it sends me the error, which is what I don't understand, as i thought I had already solved that problem with the for loops.
So if you noticed anything right off the bat that doesn't look quite right, let me know, and if you don't know anything about TIC-80 or what the API does, I'm sure the TIC-80 website can explain it way better then me.
If you want to run the game, to see the issue in action and mess around with the code, download TIC-80 from the website and run this file:
https://drive.google.com/file/d/18ti0NboNNN9Yog6l_n73usF_eX_86EN4/view?usp=sharing
Let's take a look at your bullet handling
First call to TIC:
bullets is 0. We add one bullet into bullet[0]
Second call:
bullets is 1. We add one bullet into bullet[1].
Now, as bullets > 0 we enter the bullet physics if statement.
We do some calculations to that bullet and increment bullet[0].t
The following calls we do the same. We add a bullet and process all but the new bullet as we did above.
When a bullet's t field becomes > 16 we remove it from bullet.
So first we remove the oldest bullet bullet[0]. But in the following call we again start our loop at i = 0. so bullet[i] is nil and hence indexing it in bullet[i].x causes the observed error.
Side note:
This makes no sense.
function bullet:remove()
local this = {
spr = nil,
x = nil,
y = nil,
vx = nil,
vy = nil,
mx = nil,
my = nil,
t = nil,
}
return this
end
A table with all nil values is just an empty table. So simply return an empty table.
On top of that you don't need that function as it does nothing useful.
bullet[i] = bullet:remove()
bullet[i] = nil
The first line is non necessary. You don't have to assign an emtpy table and then nil. Just assign nil.
If you'd just keep the bullets in the array part of the table you wouldn't need your own tablelength function and then subtract 2 btw.
Then you could also use table.remove to remove bullets without creating unexpected gaps in your bullet list.

iTextSharp - how to move section header to next page

When running reports using iTextSharp we can keep all the sub categories together defining a separate PdfpTable and KeepTogether = True
This works really well with sub categories that are unlikely to go over a full page.
Is there a way to move the main categories to the next page if the sub ones do not fit on that current page?
This is what we are getting
Where Expenses starts at the end of the last main category, but the sub-categories are all on the next page
This is a snippet of how they are created...
Thanks
vTable.AddCell(AddNewTextCell(True, "REVENUE", 15, ReportFontSize, False))
vTable.AddCell(Spacer_Cell(10, 15))
For Each Row As DataRow In RevenueData
Dim vInnerTable As New PdfPTable(15)
vInnerTable.KeepTogether = True
Dim vCatID As Integer = Row("ID")
vInnerTable.AddCell(AddNewTextCell(True, Row("Name"), 15, ReportFontSize, False))
Dim vSelected() As DataRow = RevenueNomDT.Select("CatID = " & vCatID, "Position")
For Each SubRow As DataRow In vSelected
SetLeftPadding = 10
vInnerTable.AddCell(AddNewTextCell(False, SubRow("NomCode") & " " & SubRow("NomName"), 2, ReportFontSize))
Dim NomCode As Integer = SubRow("NomCode")
Dim NegValue As Integer = SubRow("NegValue")
Dim vNeg As Boolean = False
If NegValue = 1 Then
vNeg = True
End If
Dim vNomType As Integer = 0
Dim vTypes() As DataRow = NLCodes.Select("NL_Code = '" & NomCode & "'", Nothing)
For Each NominalRow As DataRow In vTypes
vNomType = NominalRow("Account_Type")
Next
SetLeftPadding = 0
'12 Columns of data
For i As Integer = 0 To 11
Dim vNomValue As Decimal = 0
Dim ReportMonth As Integer = DateDiff(DateInterval.Month, ReportStartDate, ReportDate) + 1
If ReportMonth > i Then
If vNomType = 2 Then
vNomValue = ReturnMonthlyAmount(i, NomCode, True, ReportStartDate, ReportEndDate, Current_HOA_ID, vNeg)
Else
vNomValue = ReturnMonthlyAmount(i, NomCode, False, ReportStartDate, ReportEndDate, Current_HOA_ID, vNeg)
End If
RT += vNomValue
GT = DicRevenue.Item(i)
DicRevenue.Item(i) = GT + vNomValue
Dim vAmt As Decimal = DicSubs.Item(i)
DicSubs.Item(i) = vNomValue + vAmt
vInnerTable.AddCell(AddNewCurrencyCell(vNomValue, False, False, ReportFontSize))
Else
vInnerTable.AddCell(AddNewCurrencyCell(vNomValue, False, False, ReportFontSize))
End If
Next
vInnerTable.AddCell(AddNewCurrencyCell(RT, False, False, ReportFontSize))
GT = DicRevenue(12)
DicRevenue(12) = GT + RT
DicSubs.Item(12) = RT
RT = 0
Next
SetLeftPadding = 5
'Add the total of each revenue sub header
vInnerTable.AddCell(AddNewTextCell(True, "Total " & Row("Name"), 2, ReportFontSize, False))
For i As Integer = 0 To 11
vInnerTable.AddCell(AddNewCurrencyCell(DicSubs.Item(i), True, True, ReportFontSize, False))
RT += DicSubs.Item(i)
Next
vInnerTable.AddCell(AddNewCurrencyCell(RT, True, True, ReportFontSize, False))
vTable.AddCell(NoSplitTable(vInnerTable, 15))
'Remove the DictionaryValues
For i As Integer = 0 To 12
DicSubs(i) = 0
Next
RT = 0
Next
vTable.AddCell(Spacer_Cell(10, 15))
'Add in the Totals For Revenue
vTable.AddCell(AddNewTextCell(True, "TOTAL REVENUE", 2, ReportFontSize, False))
For i As Integer = 0 To 12
vTable.AddCell(AddNewCurrencyCell(DicRevenue.Item(i), True, True, ReportFontSize, False))
Next
GT = 0
RT = 0
vTable.AddCell(Spacer_Cell(20, 15))
'============================================START OF EXPENSES ==============================================
vTable.AddCell(AddNewTextCell(True, "EXPENSES", 15, ReportFontSize, False))
vTable.AddCell(Spacer_Cell(10, 15))
Private Function NoSplitTable(TableName As PdfPTable, DataColumns As Integer) As PdfPCell
Dim vCell As New iTextSharp.text.pdf.PdfPCell(TableName)
Try
With vCell
.Border = 0
.Colspan = DataColumns
End With
Return vCell
Catch ex As Exception
EmailError(ex)
Return vCell
End Try
End Function
Turned out simpler than I thought - just add subTables for each header as well
Start of one table
Dim vRevenueTable As New PdfPTable(15)
vRevenueTable.KeepTogether = True
vRevenueTable.AddCell(AddNewTextCell(True, "REVENUE", 15, ReportFontSize, False))
vRevenueTable.AddCell(Spacer_Cell(10, 15))
For Each Row As DataRow In RevenueData
Dim vInnerTable As New PdfPTable(15)
vInnerTable.KeepTogether = True
.... end of that table
vInnerTable.AddCell(AddNewCurrencyCell(RT, True, True, ReportFontSize, False))
vRevenueTable.AddCell(NoSplitTable(vInnerTable, 15))
'Remove the DictionaryValues
For i As Integer = 0 To 12
DicSubs(i) = 0
Next
RT = 0
Next
vRevenueTable.AddCell(Spacer_Cell(10, 15))
'Add in the Totals For Revenue
vRevenueTable.AddCell(AddNewTextCell(True, "TOTAL REVENUE", 2, ReportFontSize, False))
For i As Integer = 0 To 12
vRevenueTable.AddCell(AddNewCurrencyCell(DicRevenue.Item(i), True, True, ReportFontSize, False))
Next
GT = 0
RT = 0
vRevenueTable.AddCell(Spacer_Cell(20, 15))
vTable.AddCell(NoSplitTable(vRevenueTable, 15))
Besides using keeptogether-tables you can force page breaks by calling
Document.NewPage() or wrap your tables with Chapters and Sections instead of creating one big table container.
(4.1.6.0)

VB 6 failed send to email server

I am trying to write a program that will send email with an attachment in VB6. I'm using winsock and smtp.gmail.com as my mail server but it doesn't work. Failed to connect to mail server.The code works fine. My only problem is when I try to send message it doesn't connect please help me thanks in advance.
Here's the code
Dim objBase64 As New Base64
Dim bTrans As Boolean
Dim m_iStage As Integer
Dim Sock As Integer
Dim RC As Integer
Dim Bytes As Integer
Dim ResponseCode As Integer
Dim path As String
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Const OFN_READONLY = &H1
Const OFN_OVERWRITEPROMPT = &H2
Const OFN_HIDEREADONLY = &H4
Const OFN_NOCHANGEDIR = &H8
Const OFN_SHOWHELP = &H10
Const OFN_ENABLEHOOK = &H20
Const OFN_ENABLETEMPLATE = &H40
Const OFN_ENABLETEMPLATEHANDLE = &H80
Const OFN_NOVALIDATE = &H100
Const OFN_ALLOWMULTISELECT = &H200
Const OFN_EXTENSIONDIFFERENT = &H400
Const OFN_PATHMUSTEXIST = &H800
Const OFN_FILEMUSTEXIST = &H1000
Const OFN_CREATEPROMPT = &H2000
Const OFN_SHAREAWARE = &H4000
Const OFN_NOREADONLYRETURN = &H8000
Const OFN_NOTESTFILECREATE = &H10000
Const OFN_NONETWORKBUTTON = &H20000
Const OFN_NOLONGNAMES = &H40000
Const OFN_EXPLORER = &H80000
Const OFN_NODEREFERENCELINKS = &H100000
Const OFN_LONGNAMES = &H200000
Const OFN_SHAREFALLTHROUGH = 2
Const OFN_SHARENOWARN = 1
Const OFN_SHAREWARN = 0
Private Declare Function GetSaveFileName Lib "comdlg32" Alias "GetSaveFileNameA" (pOpenfilename As OPENFILENAME) As Long
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As Long, ByVal bRevert As Long) As Long
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
Private Declare Function DrawMenuBar Lib "user32" (ByVal hWnd As Long) As Long
Const MF_BYPOSITION = &H400&
Const MF_REMOVE = &H1000&
Dim Mime As Boolean
Dim arrRecipients As Variant
Dim CurrentE As Integer
Private Sub Attachment_Click()
path = SaveDialog(Me, "*.*", "Attach File", App.path)
If path = "" Then Exit Sub
AttachmentList.AddItem path
Mime = True
AttachmentList.ListIndex = AttachmentList.ListCount - 1
End Sub
Private Sub AttachmentList_Click()
fSize = Int((FileLen(AttachmentList) / 1024) * 100 + 0.5) / 100
AttachmentList.ToolTipText = AttachmentList & " (" & fSize & " KB)"
End Sub
Private Sub AttachmentList_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
For I = 1 To Data.Files.Count
If (GetAttr(Data.Files.Item(I)) And vbDirectory) = 0 Then AttachmentList.AddItem Data.Files.Item(I): Mime = True: AttachmentList.ListIndex = AttachmentList.ListCount - 1
Next I
End Sub
Private Sub DataArrival_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim MsgBuffer As String * 2048
On Error Resume Next
If Sock > 0 Then
Bytes = recv(Sock, ByVal MsgBuffer, 2048, 0)
If Bytes > 0 Then
ServerResponse = Mid$(MsgBuffer, 1, Bytes)
DataArrival = DataArrival & ServerResponse & vbCrLf
DataArrival.SelStart = Len(DataArrival)
If bTrans Then
If ResponseCode = Left$(MsgBuffer, 3) Then
m_iStage = m_iStage + 1
Transmit m_iStage
Else
closesocket (Sock)
Call EndWinsock
Sock = 0
Process = "The Server responds with an unexpected Response Code!"
Exit Sub
End If
End If
ElseIf WSAGetLastError() <> WSAEWOULDBLOCK Then
closesocket (Sock)
Call EndWinsock
Sock = 0
End If
End If
Refresh
End Sub
Private Sub delattach_Click()
If AttachmentList.ListCount = 0 Or AttachmentList.ListIndex = -1 Then Exit Sub
tmpIndex = AttachmentList.ListIndex
AttachmentList.RemoveItem (AttachmentList.ListIndex)
If AttachmentList.ListCount = 0 Then Mime = False: Attachment.ToolTipText = "Drag & Drop your attachments here" Else If AttachmentList.ListIndex = 0 Then AttachmentList.ListIndex = tmpIndex Else AttachmentList.ListIndex = tmpIndex - 1
End Sub
Sub DisableX(frm As Form)
Dim hMenu As Long
Dim nCount As Long
hMenu = GetSystemMenu(frm.hWnd, 0)
nCount = GetMenuItemCount(hMenu)
Call RemoveMenu(hMenu, nCount - 1, MF_REMOVE Or MF_BYPOSITION)
Call RemoveMenu(hMenu, nCount - 2, MF_REMOVE Or MF_BYPOSITION)
DrawMenuBar frm.hWnd
End Sub
Private Sub Exit_Click()
On Error Resume Next
Call Startrek
closesocket Sock
Call EndWinsock
End
End Sub
Private Sub Form_Load()
Call DisableX(Me)
End Sub
Function IsConnected2Internet() As Boolean
On Error Resume Next
If MyIP = "127.0.0.1" Or MyIP = "" Then IsConnected2Internet = False Else IsConnected2Internet = True
End Function
Function SaveDialog(Form1 As Form, Filter As String, Title As String, InitDir As String) As String
Dim ofn As OPENFILENAME
Dim A As Long
ofn.lStructSize = Len(ofn)
ofn.hwndOwner = Form1.hWnd
ofn.hInstance = App.hInstance
If Right$(Filter, 1) <> "|" Then Filter = Filter & "|"
For A = 1 To Len(Filter)
If Mid$(Filter, A, 1) = "|" Then Mid$(Filter, A, 1) = Chr$(0)
Next A
ofn.lpstrFilter = Filter
ofn.lpstrFile = Space$(254)
ofn.nMaxFile = 255
ofn.lpstrFileTitle = Space$(254)
ofn.nMaxFileTitle = 255
ofn.lpstrInitialDir = InitDir
ofn.lpstrTitle = Title
ofn.flags = OFN_HIDEREADONLY Or OFN_CREATEPROMPT
A = GetSaveFileName(ofn)
If (A) Then
SaveDialog = Left$(Trim$(ofn.lpstrFile), Len(Trim$(ofn.lpstrFile)) - 1)
Else
SaveDialog = ""
End If
End Function
Private Sub SendMimeAttachment()
Dim FileIn As Long
Dim temp As Variant
Dim s As Variant
Dim TempArray() As Byte
Dim Encoded() As Byte
Dim strFile As String
Dim strFile1 As String * 32768
For IAT = 0 To AttachmentList.ListCount - 1
path = AttachmentList.List(IAT)
Mimefilename = Trim$(Right$(path, Len(path) - InStrRev(path, "\")))
FileIn = FreeFile
r
temp = vbCrLf & "--NextMimePart" & vbCrLf
temp = temp & "Content-Type: application/octet-stream; name=Mimefilename" & vbCrLf
temp = temp & "Content-Transfer-Encoding: base64" & vbCrLf
temp = temp & "Content-Disposition: attachment; filename=" & Chr$(34) & Mimefilename & Chr$(34) & vbCrLf
WinsockSendData (temp & vbCrLf)
Open path For Binary Access Read As FileIn
If GetSetting(App.Title, "Settings", "Too big", "") <> "True" Then
If LOF(FileIn) > 2097152 Then
fSize = Int((LOF(FileIn) / 1048576) * 100 + 0.5) / 100
Setu = MsgBox("The current file is " & fSize & " MB of size, extracting from it could take a few minutes, Click Yes to go ahead, No to skip it or Cancel if you don't want to get this message again", vbYesNoCancel)
If Setu = vbYes Then GoTo Cont
If Setu = vbNo Then Close (FileIn): GoTo Anoth Else SaveSetting App.Title, "Settings", "Too big", "True"
End If
End If
Cont:
frm2.Visible = True
Process = "Loading """ & AttachmentList.List(IAT) & """"
Do While Not EOF(FileIn)
If LOF(FileIn) = 0 Then GoTo Anoth
Get FileIn, , strFile1
strFile = strFile & Mid$(strFile1, 1, Len(strFile1) - (Loc(FileIn) - LOF(FileIn)))
strFile1 = ""
DoEvents
frm2.Width = (3300 / 100) * (Len(strFile) * 50 / LOF(FileIn))
lblpcent = Int(Len(strFile) * 50 / LOF(FileIn)) & "%"
If Cancelflag Then Close FileIn: Exit Sub
Loop
Close FileIn
If strFile = "" Then Exit Sub
objBase64.Str2ByteArray strFile, TempArray
objBase64.EncodeB64 TempArray, Encoded
objBase64.Span 76, Encoded, TempArray
strFile = ""
s = StrConv(TempArray, vbUnicode)
For I = 1 To Len(s) Step 8192
ss = Trim$(Mid$(s, I, 8192))
tmpServerSpeed = 150
Start = timeGetTime
Do
DoEvents
Loop Until timeGetTime >= Start + tmpServerSpeed * 20
WinsockSendData (ss)
frm2.Width = 1650 + (3300 / 100) * ((I + Len(ss)) * 50 / Len(s))
lblpcent = 50 + Int((I + Len(ss)) * 50 / Len(s)) & "%"
Process = "Sending " & Mimefilename & "... " & I + Len(ss) & " Bytes from " & Len(s)
DoEvents
Next I
Anoth:
s = ""
Next IAT
WinsockSendData (vbCrLf & "--NextMimePart--" & vbCrLf)
WinsockSendData (vbCrLf & "." & vbCrLf)
End Sub
Private Sub SendMimeConnect_Click()
If Tobox = "" Or InStr(Tobox, "#") = 0 Then
MsgBox "To: Is not correct!"
Exit Sub
End If
If IsConnected = False Then
If MsgBox("No Internet connection has been detected, check for Update anyway?", vbYesNo) = vbNo Then Exit Sub
End If
Sock = ConnectSock(MailServer, 25, DataArrival.hWnd)
If Sock = SOCKET_ERROR Then
Process = "Cannot Connect to " & MailServer & GetWSAErrorString(WSAGetLastError())
closesocket Sock
Call EndWinsock
Exit Sub
End If
Process = "Connected to " & MailServer
bTrans = True
m_iStage = 0
DataArrival = ""
ResponseCode = 220
Call WaitForResponse
End Sub
Sub SendMimetxt(txtFrom, txtTo, txtSubjekt, txtMail)
Dim strToSend As String
Dim strDataToSend As String
If Mime Then
strDataToSend = "From: " & txtFrom & vbCrLf
strDataToSend = strDataToSend & "To: " & txtTo & vbCrLf
strDataToSend = strDataToSend & "Date: " & Format$(Now, "DDDD , dd Mmm YYYY hh:mm:ss AM/PM") & vbCrLf
strDataToSend = strDataToSend & "Subject: " & txtSubjekt & vbCrLf
strDataToSend = strDataToSend & "X-Mailer: " & App.CompanyName & " - " & App.Title & vbCrLf
strDataToSend = strDataToSend & "Mime-Version: 1.0" & vbCrLf
strDataToSend = strDataToSend & "Content-Type: multipart/mixed; boundary=NextMimePart" & vbCrLf
strDataToSend = strDataToSend & "Content-Transfer-Encoding: 7bit" & vbCrLf
strDataToSend = strDataToSend & "This is a multi-part message in MIME format." & vbCrLf & vbCrLf
strDataToSend = strDataToSend & "--NextMimePart" & vbCrLf & vbCrLf
strDataToSend = strDataToSend & Trim$(Mailtxt)
strDataToSend = Replace$(strDataToSend, vbCrLf & "." & vbCrLf, vbCrLf & "." & Chr$(0) & vbCrLf)
For I = 1 To Len(strDataToSend) Step 8192
strToSend = Trim$(Mid$(strDataToSend, I, 8192))
WinsockSendData (strToSend)
frm2.Width = (2400 / 100) * ((I + Len(strToSend)) * 100 / Len(strDataToSend))
lblpcent = Int((I + Len(strToSend)) * 100 / Len(strDataToSend)) & "%"
If Cancelflag Then Exit For
Process = "Sending message body... " & I + Len(strToSend) & " Bytes from " & Len(strDataToSend)
DoEvents
Next I
SendMimeAttachment
Else
strDataToSend = "From: " & txtFrom & vbCrLf
strDataToSend = strDataToSend & "To: " & txtTo & vbCrLf
strDataToSend = strDataToSend & "Date: " & Format$(Now, "DDDD , dd Mmm YYYY hh:mm:ss AM/PM") & vbCrLf
strDataToSend = strDataToSend & "Subject: " & txtSubjekt & vbCrLf
strDataToSend = strDataToSend & "X-Mailer: " & App.CompanyName & " - " & App.Title & vbCrLf & vbCrLf
strDataToSend = strDataToSend & Trim$(txtMail)
strDataToSend = Replace$(strDataToSend, vbCrLf & "." & vbCrLf, vbCrLf & "." & Chr$(0) & vbCrLf)
For I = 1 To Len(strDataToSend) Step 8192
strToSend = Trim$(Mid$(strDataToSend, I, 8192))
WinsockSendData (strToSend)
frm2.Width = (2400 / 100) * ((I + Len(strToSend)) * 100 / Len(strDataToSend))
lblpcent = Int((I + Len(strToSend)) * 100 / Len(strDataToSend)) & "%"
If Cancelflag Then Exit For
Process = "Sending message body... " & I + Len(strToSend) & " Bytes from " & Len(strDataToSend)
DoEvents
Next I
WinsockSendData (vbCrLf & "." & vbCrLf)
End If
End Sub
Sub Startrek()
On Error Resume Next
Dim Rate As Integer
Dim Rate2 As Integer
If WindowState <> 0 Then Exit Sub
Caption = "End Transmission"
GotoVal = (Height / 12)
Rate = 50
For Gointo = 1 To GotoVal
Spd = Timer
Rate2 = Rate / 2
Height = Height - Rate
Top = Top + Rate2
DoEvents
Width = Width - Rate
Left = Left + Rate2
DoEvents
If Width <= 2000 Then Exit For
Rate = (Timer - Spd) * 10000
Next Gointo
WindowState = 1
End Sub
Private Sub Tobox_Change()
arrRecipients = Split(Tobox, ",")
End Sub
Private Sub Transmit(iStage As Integer)
Dim Helo As String
Dim pos As Integer
Select Case m_iStage
Case 1
Helo = Frombox
pos = Len(Helo) - InStr(Helo, "#")
Helo = Right$(Helo, pos)
ResponseCode = 250
WinsockSendData ("HELO " & Helo & vbCrLf)
Call WaitForResponse
Case 2
ResponseCode = 250
WinsockSendData ("MAIL FROM: <" & Trim$(Frombox) & ">" & vbCrLf)
Call WaitForResponse
Case 3
ResponseCode = 250
WinsockSendData ("RCPT TO: <" & Trim$(arrRecipients(CurrentE)) & ">" & vbCrLf)
Call WaitForResponse
Case 4
ResponseCode = 354
WinsockSendData ("DATA" & vbCrLf)
Call WaitForResponse
Case 5
ResponseCode = 250
Call SendMimetxt(Frombox, Trim$(arrRecipients(CurrentE)), Subjekt, Mailtxt)
Call WaitForResponse
Case 6
ResponseCode = 221
WinsockSendData ("QUIT" & vbCrLf)
Call WaitForResponse
Process = "Email has been sent!"
frm2.Width = 3300
lblpcent = "100%"
DataArrival = ""
m_iStage = 0
If arrRecipients(CurrentE + 1) <> "" Then
CurrentE = CurrentE + 1
SendMimeConnect_Click
Else
bTrans = False
CurrentE = 0
End If
End Select
End Sub
Private Sub WaitForResponse()
Dim Start As Long
Dim Tmr As Long
Start = timeGetTime
While Bytes > 0
Tmr = timeGetTime - Start
DoEvents '
If Tmr > 20000 Then
Process = "SMTP service error, timed out while waiting for response"
End If
Wend
End Sub
Private Sub WinsockSendData(DatatoSend As String)
Dim RC As Integer
Dim MsgBuffer As String * 8192
MsgBuffer = DatatoSend
RC = send(Sock, ByVal MsgBuffer, Len(DatatoSend), 0)
If RC = SOCKET_ERROR Then
Process = "Cannot Send Request." & Str$(WSAGetLastError()) & _
GetWSAErrorString(WSAGetLastError())
closesocket Sock
Call EndWinsock
Exit Sub
End If
End Sub
I didn't bother to read your code. Too hard. Here's how to do it easily.
Set emailObj = CreateObject("CDO.Message")
emailObj.From = "dc#gail.com"
emailObj.To = "dc#gail.com"
emailObj.Subject = "Test CDO"
emailObj.TextBody = "Test CDO"
emailObj.AddAttachment "c:\windows\win.ini"
Set emailConfig = emailObj.Configuration
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "YourUserName"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Password1"
emailConfig.Fields.Update
emailObj.Send
If err.number = 0 then Msgbox "Done"
Here's how to get files from internet with a high level object. You must use the exact name with http:// as there no helper for incorrect addresses.
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com", False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
txt=File.ResponseText
Also for binary files use ado stream. To create a database in memory use adodb recordset (better than a dictionary, array, or a collection), makes sorting a one line command.

Can not create a form in vba for another active presentation

I am trying to create a form with vba and for that I am using the following code:
Private Sub createButton_Click()
Dim cSlide As Slide
Dim survey As Shape
Dim text As String
Dim top As Integer
'Dim TempForm As Object ' VBComponent
Dim FormName As String
Dim NewButton As MSForms.CommandButton
Dim TextLocation As Integer
' ** Additional variable
Dim X As Integer
If singleOption.value Then
typ = "radio"
Else
If multipleOption.value Then
typ = "checkBox"
Else
If dropdown.value Then
typ = "dropdown"
Else
MsgBox "Please, select survey type before continue"
Exit Sub
End If
End If
End If
If tagBox = "" Then
MsgBox "Please, write a title before continue"
Exit Sub
End If
If choiceNum = "" Then
MsgBox "Please, set the options number"
Exit Sub
End If
'Locks Excel spreadsheet and speeds up form processing
Application.VBE.MainWindow.Visible = False
'Application.ScreenUpdating = False
choNum = choiceNum
' Create the UserForm
Set TempForm = ActivePresentation.VBProject.VBComponents.Add(vbext_ct_MSForm)
'TempForm.Activate
'Set Properties for TempForm
With TempForm
.Properties("Caption") = "Possible answers"
.Properties("Width") = 300
.Properties("Height") = 10 + 34 * choiceNum + 50
End With
FormName = TempForm.Name
For i = 1 To choiceNum
Set newTab = TempForm.Designer.Controls.Add("Forms.Label.1", "label" & i, True)
With newTab
.Caption = "Answer" & i
.width = 40
.height = 15
.top = 10 + 30 * (i - 1)
.left = 10
End With
Set cCntrl = TempForm.Designer.Controls.Add("Forms.TextBox.1", "textBox" & i, True)
With cCntrl
.width = 150
.height = 15
.top = 10 + 30 * (i - 1)
.left = 60
.ZOrder (0)
End With
Next i
Set NewButton = TempForm.Designer.Controls.Add("forms.CommandButton.1", "answerButton", True)
With NewButton
.Caption = "Create survey"
.left = 60
.top = 30 * choiceNum + 10
End With
ActiveWindow.Selection.Unselect
Set cSlide = Application.ActiveWindow.View.Slide
Set survey = cSlide.Shapes.AddTextbox(msoTextOrientationHorizontal, 20, 20, 400, 20)
survey.TextFrame.TextRange.Font.Size = 25
survey.TextFrame.TextRange.text = tagBox
height = survey.height
survey.Select
'X = ActivePresentation.VBProject.VBComponents(FormName).CodeModule.CountOfLines
With TempForm.CodeModule
X = .CountOfLines + 1
.InsertLines X + 1, "Sub answerButton_Click()"
.InsertLines X + 2, " Dim cSlide As Slide"
.InsertLines X + 3, " Dim survey As Shape"
.InsertLines X + 4, " Dim top As Integer"
.InsertLines X + 5, " Set cSlide = Application.ActiveWindow.View.Slide"
.InsertLines X + 6, " top = 30 + surveyCreation.height - 20"
.InsertLines X + 7, " "
.InsertLines X + 8, " For i = 1 To surveyCreation.choNum"
.InsertLines X + 9, " "
.InsertLines X + 10, " top = top + 15"
.InsertLines X + 11, " Set survey = cSlide.Shapes.AddTextbox(msoTextOrientationHorizontal, 30, top, 400, 10)"
.InsertLines X + 12, " survey.TextFrame.TextRange.text = Me.Controls(i * 2 - 1).Text"
.InsertLines X + 13, " "
.InsertLines X + 14, " survey.TextFrame.TextRange.ParagraphFormat.Bullet = True"
.InsertLines X + 15, " survey.TextFrame.TextRange.ParagraphFormat.Bullet.Type = ppBulletUnnumbered"
.InsertLines X + 16, " survey.Select Replace:=False"
.InsertLines X + 17, " Next i"
.InsertLines X + 18, " With ActiveWindow.Selection.ShapeRange"
.InsertLines X + 19, " .Group.title = ""Dink survey creation"" & surveyCreation.typ"
.InsertLines X + 20, "End With"
.InsertLines X + 21, "Application.VBE.ActiveVBProject.VBComponents.Remove Application.VBE.ActiveVBProject.VBComponents(Application.VBE.ActiveVBProject.VBComponents.Count)"
.InsertLines X + 22, "End Sub"
End With
'TempForm.Activate
tagBox.text = ""
choiceNum = ""
'ActivePresentation.VBProject.VBComponents.Add vbext_ct_MSForm
surveyCreation.Hide
'TempForm.Show
VBA.UserForms.Add(FormName).Show
ActivePresentation.VBProject.UserForms
End Sub
It is working well if I run the code in the presentation were I create the macro but if I want to exec it in another other it gives me the "object required" error. I try with ActivePresentation.VBA witch is not even compiling.
EDIT:
I create a ppam file and add it to powerpoint but it is giving me the same problem even in the presentation were I create it. So if I exec the code in the presentation were I create it, it works. But if I exec the ppam code (I add a button to exec it) it is giving me object required error.
OK, I have had some time to test this out.
I add some code which will create a standard code module at runtime in the ActivePresentation, with one subroutine called ShowMe. This subroutine can then be called from:
Application.Run ActivePresentation.Name & "!ShowMe"
Here is the sample code. I have tested it in a PPAM file and it successfully creates & shows the UserForm in the ActivePresentation.
Option Explicit
Sub Test()
Dim TempForm As Object 'VBComponent / Late Binding
Dim showModule As Object 'VBComponent
Dim FormName As String
Dim choiceNum As Long: choiceNum = 3
Dim vbComps As Long
Dim X As Long
Set TempForm = ActivePresentation.VBProject.VBComponents.Add(3) 'vbext_ct_MSForm
With TempForm
.Properties("Caption") = "Possible answers"
.Properties("Width") = 300
.Properties("Height") = 10 + 34 * choiceNum + 50
FormName = .Properties("Name")
End With
'## Insert a standard code module which will contain a subroutine to show the TempForm
Set showModule = ActivePresentation.VBProject.VBComponents.Add(1) 'vbext_ct_StdModule
With showModule.CodeModule
X = .CountOfLines + 1
.InsertLines X + 1, "Sub ShowMe()"
.InsertLines X + 2, " " & FormName & ".Show"
.InsertLines X + 3, "End Sub"
End With
Application.Run ActivePresentation.Name & "!ShowMe"
'## Remove the module & user form created, above
ActivePresentation.VBProject.VBComponents.Remove TempForm
ActivePresentation.VBProject.VBComponents.Remove showModule
'## Clean up
Set TempForm = Nothing
Set showModule = Nothing
End Sub
While I think there is maybe another way of achieving this (similar to what you were trying with a .Show method), I was not able to make that work. The above method seems to be reliable.
NOTE I am using Option Explicit. Your code has undeclared variables so this will raise some warnings and your code will not execute until you clean it up.
I haven't studied the code in detail, but choose the File menu (Backstage View in 2010) PowerPoint Options, Trust Center, click Trust Center Settings and check "Trust access to the vba project object model".