vb.net chart: How to get AxisX.CustomLabels in sync with AxisX.MajorTickMark - vb.net

As shown in the code, I get CustomLabels displayed, but they are not on the MajorTickMarks defined in the ChartArea. How do I get this in sync?
vb.net
Dim from_X, to_X As Date
from_X = myClass.get_DateOfWeek(CInt(yearkNo), CInt(weekNo), DayOfWeek.Monday)
'Last week from mainTable
weekNo = mainTable.Columns(mainTable.Columns.Count - 1).ColumnName.Split(CChar("/"))(0).Substring(2, 2)
yearkNo = mainTable.Columns(mainTable.Columns.Count - 1).ColumnName.Split(CChar("/"))(1).Substring(0, 4)
to_X = myClass.get_DateOfWeek(CInt(yearkNo), CInt(weekNo), DayOfWeek.Saturday)
Dim ints as integer = CInt(DateDiff(DateInterval.WeekOfYear, from_X, to_X, FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFullWeek))
Dim xdate(ints) As Date 'is looped through and the date of the respective week is added.
newchart(chart1) 'create new chart
Dim chartArea1 As New ChartArea("Default")
chart1.ChartAreas.Add(chartArea1)
chart1.ChartAreas("Default").AxisX.IntervalType = DateTimeIntervalType.Weeks
chart1.ChartAreas("Default").AxisX.Interval = 1
chart1.ChartAreas("Default").AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont
chart1.ChartAreas("Default").AxisX.LabelAutoFitMinFontSize = 7
chart1.ChartAreas("Default").AxisX.LabelStyle.Font = My.Settings.fontbold8
chart1.ChartAreas("Default").AxisX.LabelStyle.Angle = 90
chart1.ChartAreas("Default").AxisX.MajorTickMark.Enabled = True
chart1.ChartAreas("Default").AxisX.MinorTickMark.Enabled = False
chart1.ChartAreas("Default").AxisX.Minimum = from_X.ToOADate()'44443
chart1.ChartAreas("Default").AxisX.Maximum = to_X.ToOADate()'44828
chart1.ChartAreas("Default").AxisX.IsMarginVisible = False
chart1.Series.Add("K").Color = ColorTranslator.FromHtml("#297AB7") 'MattBlau colorx(0)
chart1.Series("K").Points.DataBindXY(xdate, yValues)
chart1.ChartAreas("Default").AxisX.CustomLabels.Clear()
For intVal As Integer = 0 To ints - 1
Debug.Print(intVal & " - " & Format(xdate(intVal), "yyyy-MM-dd"))
Select Case intVal
Case 0, 5, 10, 15, 20, ints - 2
chart1.ChartAreas("Default").AxisX.CustomLabels.Add(xdate(intVal).ToOADate(), xdate(ints - 1).ToOADate(), myClass.get_WeekNumber(xdate(intVal)) & "/" & xdate(intVal).Year)
End Select
Next
It looks now like here in the picture:
https://www.spearhead-home.com/Downloads/20220517_XAchseKWs.jpg
Found now a solution for me:
AxisX.IntervalType, AxisX.Minimum, AxisX.Maximum must match the series DataBindXY(xValues, yValues)
Dim ints as integer = CInt(DateDiff(DateInterval.WeekOfYear, von_X, bis_X, _
FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFullWeek))
Dim xdate(ints) As Date 'is looped through and the date of the respective week is added.
Dim xInt(ints) As Integer 'is looped through and the numbers of the interval-count added.
chart1.ChartAreas("Default").AxisX.IntervalType = DateTimeIntervalType.NotSet
chart1.ChartAreas("Default").AxisX.Interval = 1
chart1.ChartAreas("Default").AxisX.Minimum = 0
chart1.ChartAreas("Default").AxisX.Maximum = ints - 1
chart1.ChartAreas("Default").AxisX.CustomLabels.Clear()
For intVal As Integer = 0 To ints - 1
Dim kw_run As String = ""
kw_run = myClass.set_WeekFormat(myClass.get_WeekNumber(xdate(intVal)), xdate( _
intVal), True)
'result looks like: 2022/20
chart1.ChartAreas("Default").AxisX.CustomLabels.Add(intVal, intVal + 1, kw_run, _
0, LabelMarkStyle.None)
Next
'Series
chart1.Series("mySeries").Points.DataBindXY(xInt, yValues)
'...

Related

Count lines not 0 found Textboxes

I want to calculate the amount in a multiline Textbox where the value 0 is not found.
If TxtListScanValue.Text = ("2") Then
TxtDrawR2.Text &= Environment.NewLine & lastDraw2
Dim ListScan = TxtNumberListScan.Lines.ToList.Select(Function(o, i) New With {.scan = o, .Index = i})
Dim DrawR2 = TxtDrawR2.Lines.ToList.Select(Function(o, i) New With {.draw = o, .Index = i})
Dim list2 = From a In ListScan From b In DrawR2 Where a.Index = b.Index Select LstScan = a.scan, DrwR2 = ("00" & b.draw).Substring(("00" & b.draw).Length - 2) Order By DrwR2 Descending
TxtListScanTxt.Text = String.Join(vbCrLf, list2)
End If
If TxtdrawR5 =
2
4
0
0
1
3
5
In output I want to display: 5 because:
I want to calculate the count lines where the value 0 is not found. Count lines no have 0 value :D (2+4+1+3+5 = 5) (5 lines no have 0 value).
You create function like this:
'For Counting
Private Function CountNonZero(ByVal TheCtrl As TextBox) As Integer
Dim myCnt As Integer = 0
For Each Content In TheCtrl.Lines
Dim ContentVal As Integer = 0
Integer.TryParse(Content, ContentVal)
If ContentVal <> 0 Then myCnt += 1
Next
Return myCnt
End Function
'For Counting
Private Function SummingNonZero(ByVal TheCtrl As TextBox) As Integer
Dim mySum As Integer = 0
For Each Content In TheCtrl.Lines
Dim ContentVal As Integer = 0
Integer.TryParse(Content, ContentVal)
If ContentVal <> 0 Then mySum += ContentVal
Next
Return mySum
End Function
And you can count or sum now:
dim TxtdrawR5Count as integer = CountNonZero(TxtdrawR5)
dim TxtdrawR5Sum as integer = SummingNonZero(TxtdrawR5)

How to convert Julian date ignoring the year to Julian Day

How do i convert day/Month to Julian Day in visual basic?
Formula for converting in other languages are also appreciated.
For e.g
Julian Day for 1 Feb=032
https://landweb.modaps.eosdis.nasa.gov/browse/calendar.html
From research in the web ,most resolutions are converting the date with yyyy-mm-dd to julian date.
As the example above, i need to get value 032
The .Net JulianCalendar Class exposes all methods needed to achieve your goal. It is also COM visible, so you can reference it in a VBA project after adding a project reference to "mscorlib.dll".
In VB.Net the code would be:
Dim jc As New System.Globalization.JulianCalendar
' create a gregorian equivalent of the julian date: 1 Feb 2018
Dim gregoriaDateEquivalent As DateTime = jc.ToDateTime(2018, 2, 1, 0, 0, 0, 0)
' = #2/14/2018 12:00:00 AM#
Dim dayOfYear As Int32 = jc.GetDayOfYear(gregoriaDateEquivalent)
' = 32
In VBA the code would be:
Dim jc As mscorlib.JulianCalendar
Set jc = New mscorlib.JulianCalendar
' create a gregorian equivalent of the julian date: 1 Feb 2018
Dim gregoriaDateEquivalent As Date
gregoriaDateEquivalent = jc.ToDateTime(2018, 2, 1, 0, 0, 0, 0)
' = #2/14/2018
Dim dayOfYear As Long
dayOfYear = jc.GetDayOfYear(gregoriaDateEquivalent)
' = 32
First you have to add reference to mscorlib library
Under VB6,Project-References->Tick the mscorlib checkbox
Create this function method in the object that you ahve or otherwise create a sub procedure
Public Function JulianConverter() As String
'MsgBox Fix(5.2), vbExclamation, App.Title
'MsgBox Fix(5.6)
Dim y As String
Dim m As String
Dim d As String
Dim strDate As String
Dim dateArray() As String
strDate = Format(Now, "dd/MMM/yyyy")
dateArray = Split(strDate, "/")
d = dateArray(0)
m = dateArray(1)
y = dateArray(2)
'Debug
'MsgBox strDate
'Convert to Integer
y = Val(y)
m = Val(m)
d = Val(d)
If m <= 2 Then
y = y - 1
m = m + 12
End If
'Dim A As Double
' Dim B As Double
'Dim JD As Double
' A = CDbl(Fix(y / 100#))
'B = 2 - A + Fix(A / 4)
'JD = Fix(365.25 * (y + 4716)) + Fix(30.6001 * (m + 1)) + d + B - 1524.5
'JulianConverter = CStr(JD) 'Convert to string
Dim jc As mscorlib.JulianCalendar
Set jc = New mscorlib.JulianCalendar
' create a gregorian equivalent of the julian date: 1 Feb 2018
Dim gregoriaDateEquivalent As Date
gregoriaDateEquivalent = jc.ToDateTime(2018, m, d, 0, 0, 0, 0)
' = #2/14/2018
Dim dayOfYear As Long
Dim dayOfYearS As String
Dim digitLength As Integer
Dim Counter As Integer
dayOfYear = jc.GetDayOfYear(gregoriaDateEquivalent)
'Have to ensure 3 digits values
dayOfYearS = CStr(dayOfYear)
'Count number of Digits of string
digitLength = Len(dayOfYearS)
MsgBox "DigitLength" & digitLength, vbExclamation, App.Title
'If Digits length smaller than 3,add one 0 in front
If (digitLength < 3) Then
dayOfYearS = "0" & dayOfYearS
End If
JulianConverter = dayOfYearS
End Function
This will ensure the julian day will be 3 digits in value based on the current system date

TA-Lib using TA_INTEGER_DEFAULT and TA_REAL_DEFAULT in VB.NET 2010

VB.NET 2010 below is working. But I need to use default values as stated in TA-Lib documentation: TA_INTEGER_DEFAULT or TA_REAL_DEFAULT for optional parameters. How I can use that in coding?
Currently I assign values manually (need to know what are the values).
Public Sub CalcMACD()
' CALCULATE allocationSize
Dim lookback As Integer = TicTacTec.TA.Library.Core.MacdLookback(optInFastPeriod, optInSlowPeriod, optInSignalPeriod)
Dim temp As Integer = Math.Max(lookback, startIdx)
If (temp > endIdx) Then
allocationSize = 0 ' No output
Else
allocationSize = endIdx - temp + 1
End If
optInFastPeriod = 12 ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT
optInSlowPeriod = 26 ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT
optInSignalPeriod = 9 ' Set optional values <==== HOW TO USE TA_INTEGER_DEFAULT
Dim outMACD As Double() ' Declare output variable type
ReDim outMACD(allocationSize)
Dim outMACDSignal As Double() ' Declare output variable type
ReDim outMACDSignal(allocationSize)
Dim outMACDHist As Double() ' Declare output variable type
ReDim outMACDHist(allocationSize)
' the calculation
Dim res As TicTacTec.TA.Library.Core.RetCode = TicTacTec.TA.Library.Core.Macd(startIdx, endIdx, openPrice, optInFastPeriod, optInSlowPeriod, optInSignalPeriod, outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist)
' Add result column to Datagridview
' #1 add column to Datagridview1
DataGridView1.ColumnCount = DataGridView1.ColumnCount + 3
Dim columnID As Integer = DataGridView1.ColumnCount - 3
' #2 define column header
DataGridView1.Columns(columnID).HeaderText = "MACD"
DataGridView1.Columns(columnID + 1).HeaderText = "MACD Signal"
DataGridView1.Columns(columnID + 2).HeaderText = "MACD Histogram"
'#3 insert values to column
For i As Integer = startIdx To endIdx
DataGridView1(columnID, i).Value = outMACD(i)
DataGridView1(columnID + 1, i).Value = outMACDSignal(i)
DataGridView1(columnID + 2, i).Value = outMACDHist(i)
Next
End Sub
Public Sub CalcMACD(Optional ByVal optInFastPeriod As Integer = TA_INTEGER_DEFAULT, Optional ByVal optInSlowPeriod As Integer = TA_INTEGER_DEFAULT, Optional ByVal optInSignalPeriod As Integer = TA_INTEGER_DEFAULT)
' CALCULATE allocationSize
Dim allocationSize As Integer = 0
Dim lookback As Integer = TicTacTec.TA.Library.Core.MacdLookback(optInFastPeriod, optInSlowPeriod, optInSignalPeriod)
Dim temp As Integer = Math.Max(lookback, startIdx)
If (temp < endIdx) Then
allocationSize = endIdx - temp + 1
End If
' Declare output variables
Dim outMACD(allocationSize) As Double
Dim outMACDSignal(allocationSize) As Double
Dim outMACDHist(allocationSize) As Double
' the calculation
Dim res As TicTacTec.TA.Library.Core.RetCode = TicTacTec.TA.Library.Core.Macd(startIdx, endIdx, openPrice, optInFastPeriod, optInSlowPeriod, optInSignalPeriod, outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist)
' Add result column to Datagridview
' #1 add column to Datagridview1
DataGridView1.ColumnCount = DataGridView1.ColumnCount + 3
Dim columnID As Integer = DataGridView1.ColumnCount - 3
' #2 define column header
DataGridView1.Columns(columnID).HeaderText = "MACD"
DataGridView1.Columns(columnID + 1).HeaderText = "MACD Signal"
DataGridView1.Columns(columnID + 2).HeaderText = "MACD Histogram"
'#3 insert values to column
For i As Integer = startIdx To endIdx
DataGridView1(columnID, i).Value = outMACD(i)
DataGridView1(columnID + 1, i).Value = outMACDSignal(i)
DataGridView1(columnID + 2, i).Value = outMACDHist(i)
Next
End Sub

Excel VBA: Variable as First Row of Selection?

I am creating a function in Excel VBA. I am trying to set a variable equal to the first cell in a selection on the worksheet. Basically the equivalent of something like
x = Worksheets("Data").Range("D2").Offset(i - 1, 0)
y = Worksheets("Data").Range("E2").Offset(i - 1, 0)
z = Worksheets("Data").Range("F2").Offset(i - 1, 0)
except I want "Range("D2")" E2 and F2 to instead refer to the first, second and third cell of whatever I've got highlighted on the sheet, rather than a preset cell.
The specific code I've got is:
Function VarunModel(Table As Range, Optional EndCondition As Integer = 0) As Variant
Dim iNumCols As Integer, iNumRows As Integer
Dim i As Integer
Dim SelectedRange As Range
Set SelectedRange = Selection
iNumCols = Table.Columns.Count
iNumRows = Table.Rows.Count
maturity = Worksheets("KMV-Merton").Range("B2").Value
For i = 1 To iNumRows
equity(i) = SelectedRange.Cells(1).Value
debt(i) = SelectedRange.Cells(2).Value
riskFree(i) = Selection.Cells(3).Value
Next i
Dim equityReturn As Variant: ReDim equityReturn(2 To iNumRows)
Dim sigmaEquity As Double
Dim asset() As Double: ReDim asset(1 To iNumRows)
Dim assetReturn As Variant: ReDim assetReturn(2 To iNumRows)
Dim sigmaAsset As Double, meanAsset As Double
Dim x(1 To 1) As Double, n As Integer, prec As Double, precFlag As Boolean, maxDev As Double
For i = 2 To iNumRows: equityReturn(i) = Log(equity(i) / equity(i - 1)): Next i
sigmaEquity = WorksheetFunction.StDev(equityReturn) * Sqr(260)
sigmaAsset = sigmaEquity * equity(iNumRows) / (equity(iNumRows) + debt(iNumRows))
NextItr: sigmaAssetLast = sigmaAsset
For iptr = 1 To iNumRows
x(1) = equity(iptr) + debt(iptr)
n = 1
prec = 0.00000001
Call NewtonRaphson(n, prec, x, precFlag, maxDev)
asset(iptr) = x(1)
Next iptr
For i = 2 To iNumRows: assetReturn(i) = Log(asset(i) / asset(i - 1)): Next i
sigmaAsset = WorksheetFunction.StDev(assetReturn) * Sqr(260)
meanAsset = WorksheetFunction.Average(assetReturn) * 260
If (Abs(sigmaAssetLast - sigmaAsset) > prec) Then GoTo NextItr
Dim disToDef As Double: disToDef = (Log(asset(iNumRows) / debt(iNumRows)) + (meanAsset - sigmaAsset ^ 2 / 2) * maturity) / (sigmaAsset * Sqr(maturity))
Dim defProb As Double: defProb = WorksheetFunction.NormSDist(-disToDef)
VarunModel = defProb
End Function
Thanks.
Try the below code
Dim SelectedRange As Range
Set SelectedRange = Selection
x = SelectedRange.Cells(1).Value
y = SelectedRange.Cells(2).Value
z = SelectedRange.Cells(3).Value
try this:
Dim Row as integer
Dim Col as Integer
Row = 2
Col = 4 'column "D"
x = Worksheets("Data").cells(row, col).Offset(i - 1, 0)
col = col + 1
y = Worksheets("Data").cells(row, col).Offset(i - 1, 0)
col = col + 1
z = Worksheets("Data").cells(row, col).Offset(i - 1, 0)
See the example below for using the selection on the excel, you can control the column you want by changing the column index. If you select only 1 cell, it will also work:
Sub Solution()
x = Selection.Cells(1, 0) 'By using the zero index on the column, it will get the left cell from the selected one.
y = Selection.Cells(2, 0)
Z = Selection.Cells(3, 0)
End Sub

vb.net - How can I change the type of values that the DataTable can store?

I want to add characters (like % and pp) in values stored in a DataTable, but I'm getting an error message:
Input string was not in a correct format.Couldn't store <97.0%> in Actual Column. Expected type is Decimal.
How can I change the type of values that the DataTable can store?
Dim dv As New System.Data.DataView
Dim dt As New System.Data.DataTable
dv = SQL_Customer.Select(DataSourceSelectArguments.Empty)
dt = dv.ToTable()
dt.Rows(1)(1) = CStr(dt.Rows(1)(1)) & "%"
dt.Rows(1)(2) = CStr(dt.Rows(1)(2)) & "%"
dt.Rows(1)(3) = CStr(dt.Rows(1)(3)) & "%"
dt.Rows(1)(4) = CStr(dt.Rows(1)(4)) & "pp"
You can't change the type of a data table column once it's filled.
One work around is to add a new column of type string and then populate that column with the string values you need and then delete the column that is of the type you don't need.
If this helps someone, this is how I resolved the problem:
Dim dv As New System.Data.DataView
Dim dt As New System.Data.DataTable
Dim dt2 As New System.Data.DataTable
Dim SelectedIndex As Object
If datagrid.SelectedIndex = "-1" Then SelectedIndex = 0 Else SelectedIndex = GV_Cust.SelectedIndex
'Populate Dataview with data in SQL Query for Customer KPIs
dv = SQL_Customer.Select(DataSourceSelectArguments.Empty)
'Populate table with data from dataview. Note that the data is formated as per data loaded. So if number is loaded, then format for the cell is number. This creates a problem when adding percentages
dt = dv.ToTable()
'New colums are added as string format in the dataTable so that % and pp can be added
Dim column As DataColumn
For i = 1 To 6
' Create second column.
column = New DataColumn()
column.DataType = System.Type.GetType("System.String")
column.ColumnName = i
column.AutoIncrement = False
column.Caption = i
column.ReadOnly = False
column.Unique = False
' Add the Column to the DataColumnCollection.
dt.Columns.Add(column)
Next
'New columns are populated and calculations for variances are calculated
For j = 0 To 2
For i = 0 To 4
dt.Rows(i)(7 + j) = dt.Rows(i)(1 + j) & "%"
dt.Rows(i)(10) = (dt.Rows(i)(1) - dt.Rows(i)(2)) & "pp"
dt.Rows(i)(11) = (dt.Rows(i)(1) - dt.Rows(i)(3)) & "pp"
dt.Rows(i)(12) = (dt.Rows(i)(2) - dt.Rows(i)(3)) & "pp"
Next
For i = 5 To 6
dt.Rows(i)(7 + j) = dt.Rows(i)(1 + j)
If dt.Rows(i)(2) = 0 Then dt.Rows(i)(10) = 0 & "%" Else dt.Rows(i)(10) = Math.Round((((dt.Rows(i)(1) / dt.Rows(i)(2))) - 1) * 100, 1) & "%"
If dt.Rows(i)(3) = 0 Then dt.Rows(i)(11) = 0 & "%" Else dt.Rows(i)(11) = Math.Round((((dt.Rows(i)(1) / dt.Rows(i)(3))) - 1) * 100, 1) & "%"
If dt.Rows(i)(3) = 0 Then dt.Rows(i)(12) = 0 & "%" Else dt.Rows(i)(12) = Math.Round((((dt.Rows(i)(2) / dt.Rows(i)(2))) - 1) * 100, 1) & "%"
Next
Next
'Old columns are deleted and new wones are renamed
dt.Columns.Remove("A")
dt.Columns("1").ColumnName = "A"
dt.Columns.Remove("B")
dt.Columns("2").ColumnName = "B
dt.Columns.Remove("C")
dt.Columns("3").ColumnName = "C"
dt.Columns.Remove("D")
dt.Columns("4").ColumnName = "D"
dt.Columns.Remove("D")
dt.Columns("5").ColumnName = "E"
dt.Columns.Remove("F")
dt.Columns("6").ColumnName = "F"
'Customer grid is populated, a selection button is added and the first row is selected
datagrid.DataSource = dt
datagrid.AutoGenerateSelectButton = True
datagrid.DataBind()
datagrid.SelectedIndex = SelectedIndex