Visual Basic.NET - Problema con BackGroundWorker

 
Vista:
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por José Vicente (113 intervenciones) el 28/10/2021 11:13:11
Hola, tengo un BackGroundWorker para actualizar una hoja Excel en segundo plano y el problema que tengo es que la barra de progreso que he insertado no se actualiza, la hoja se actualiza y el RunWorkedCompleted si lo hace. Dejo el código para ver si me podéis echar una mano. Gracias.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
Sub worker_Dowork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
 
        'REALIZAMOS EL PROCESO EN SEGUNDO PLANO. ACTUALIZANDO LA HOJA EXCEL
 
        Dim anio As String = CStr(Now.Year) 'EXTRAEMOS EL AÑO DE LA FECHA ACTUAL
            Dim comienzo As DateTime = DateTime.Now
            e.Result = ""
 
            exApp = New Excel.Application
            exLibro = exApp.Workbooks.Open("D:\Documentos\Escaneados\Informe_medico_infarto_2019\Tensión\Historico tension.xlsx")
            exHoja = DirectCast(exLibro.Sheets("Histórico tensión " & anio), Excel.Worksheet)
 
            Dim ultimaFila As Int16 = exHoja.Range("A1").End(Excel.XlDirection.xlDown).Row 'VALOR DE LA ÚLTIMA FILA CON DATOS
            Dim menorFecha As String = Format(exHoja.Range("$A$" & ultimaFila).Value, "dd/MM/yyyy") 'VALOR DE LA ÚLTIMA FECHA INSERTADA EN LA HOJA
            Dim rowIndex As Int16 = 0
            Dim primeraVacia As String = ("A" & ultimaFila + 1) 'PRIMERA FILA VACÍA
 
            'SELECCIONO LA PRIMERA CELDA VACÍA DESPUÉS DE LA ÚLTIMA FILA ESCRITA
 
            exHoja.Select()
            exHoja.Range(primeraVacia).Select()
 
            Dim actualizaSQL As String = "SELECT * FROM valores WHERE fecha > '" & CDate(menorFecha) & "';"
 
            'ESTABLECEMOS CONEXIÓN CON POSTGRES
 
            If conexion.State = ConnectionState.Open Then
                conexion.Close()
 
            Else conexion.Open()
 
            End If
 
            Dim SQLadapter As New NpgsqlDataAdapter(actualizaSQL, conexion)
            Dim ds As New DataSet
 
            'RELLENAMOS EL DATASET Y AÑADIMOS REGISTROS AL EXCEL
 
            SQLadapter.Fill(ds)
 
            For i = 0 To ds.Tables(0).Rows.Count - 1 'RECORREMOS LAS FILAS DEL DATASET
 
                For j = 0 To ds.Tables(0).Columns.Count - 1 'RECORREMOS LAS COLUMNAS DEL DATASET
 
                    exHoja.Cells(ultimaFila + 1, j + 1) = ds.Tables(0).Rows(i).Item(j) 'RELLENAMOS LAS CELDAS EXCEL CON LOS NUEVOS VALORES
 
                Next
 
                ultimaFila += 1
 
            Next
 
            'FORMATEAMOS, GUARDAMOS Y CERRAMOS EL EXCEL
 
            Dim M_Izq As Short = 63
            Dim M_Der As Short = 43
            Dim M_Sup As Short = 35
            Dim M_Inf As Short = 40
 
            'ORIENTACIÓN DE LA HOJA
 
            With exHoja.PageSetup
 
                .Orientation = Excel.XlPageOrientation.xlPortrait
 
                'CONFIGURACIÓN DE MÁRGENES
 
                .LeftMargin = M_Izq
                .RightMargin = M_Der
                .TopMargin = M_Sup
                .BottomMargin = M_Inf
 
            End With
 
            'TÍTULO EN NEGRITA, ALINEADO AL CENTRO DE LAS CELDAS Y COLOR
 
            Dim objRango As Excel.Range = exHoja.Range(exHoja.Cells(1, 1), exHoja.Cells(exHoja.UsedRange.Rows.Count, exHoja.UsedRange.Columns.Count))
            Dim contador As Integer = exHoja.Rows.Count
 
            exHoja.PageSetup.PrintTitleRows = exHoja.Rows(1).Address 'PONEMOS LA FILA DE ENCABEZADO EN TODAS LAS HOJAS IMPRESAS
            exHoja.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4 'TAMAÑO DE PAPEL A4
 
            exHoja.Rows.Item(1).Font.Bold = 1 'NEGRITA
            exHoja.Rows.Item(1).Font.ColorIndex = 49 'COLOR DEL ENCABEZADO
            exHoja.Rows.Item(1).HorizontalAlignment = 3 'ALINEADO DEL ENCABEZADO
 
            objRango.Borders.LineStyle = 1 'BORDES DE LA HOJA
            objRango.HorizontalAlignment = 3 'ALINEADO DE LAS COLUMNAS
 
            exHoja.Rows.Font.Size = 12 ' TAMAÑO DE LA FUENTE
            exHoja.Rows.Font.Name = "Adobe Garamond Pro Bold" 'TIPO DE FUENTE
 
            exHoja.Columns.AutoFit() 'AJUSTE DE LAS COLUMNAS
 
            exHoja.Range("A2:A367").Font.ColorIndex = 5 'COLOR DE LA FUENTE DE LA COLUMNA DE FECHAS
            exHoja.Range("A2:A367").Interior.Color = Color.White 'COLOR DEL FONDO DE LA COLUMNA FECHAS
            exHoja.Range("A2:A367").NumberFormat = "dd/mm/yyyy"
 
 
            'DAMOS FORMATO CONDICIONAL A LAS CELDAS
            'FORMATO A COLUMNA DE FECHA
 
            Dim NCol As Short = DataGridView1.ColumnCount
            Dim NRow As Short = DataGridView1.RowCount
 
            For Fila As Short = 2 To NRow + 1
 
                For Col As Short = 2 To NCol
 
                    Dim FC As String = Chr(64 + Col) & Fila
 
                    exHoja.Range(FC).Select()
                    exHoja.Range(FC).Font.ColorIndex = 1
                    exHoja.Range(FC).Font.Bold = True
 
                Next
 
            Next
 
            'FORMATO A COLUMNA SISTÓLICA
 
            For Fila As Short = 2 To NRow + 1
 
                For Col As Short = 2 To NCol - 3
 
                    Dim FC As String = Chr(64 + Col) & Fila
 
                    exHoja.Range(FC).Select()
 
                    If exHoja.Range(FC).Value >= 15 Or exHoja.Range(FC).Value <= 11 Then
 
                        exHoja.Range(FC).Font.ColorIndex = 3
                        exHoja.Range(FC).Font.Bold = True
 
                    End If
 
                Next
 
            Next
 
            'FORMATO A COLUMNA DIASTÓLICA
 
            For Fila As Short = 2 To NRow + 1
 
                For Col As Short = 3 To NCol - 2
 
                    Dim FC As String = Chr(64 + Col) & Fila
 
                    exHoja.Range(FC).Select()
 
                    If exHoja.Range(FC).Value <= 5 Or exHoja.Range(FC).Value >= 8 Then
 
                        exHoja.Range(FC).Font.ColorIndex = 3
                        exHoja.Range(FC).Font.Bold = True
 
                    End If
 
                Next
 
            Next
 
            'FORMATO A COLUMNA PULSACIONES
 
            For Fila As Short = 2 To NRow + 1
 
                For Col As Short = 4 To NCol - 1
 
                    Dim FC As String = Chr(64 + Col) & Fila
 
                    exHoja.Range(FC).Select()
 
                    If exHoja.Range(FC).Value <= 50 Or exHoja.Range(FC).Value > 75 Then
 
                        exHoja.Range(FC).Font.ColorIndex = 3
                        exHoja.Range(FC).Font.Bold = True
 
                    End If
 
                Next
 
            Next
 
            'FORMATO A COLUMNA SATURACIÓN
 
            For Fila As Short = 2 To NRow + 1
 
                For Col As Short = 5 To NCol
 
                    Dim FC As String = Chr(64 + Col) & Fila
 
                    exHoja.Range(FC).Select()
 
                    If exHoja.Range(FC).Value <= 96 Then
 
                        exHoja.Range(FC).Font.ColorIndex = 3
                        exHoja.Range(FC).Font.Bold = True
 
                    End If
 
                Next
 
            Next
 
            'ELIMINAMOS RESIDUOS DE VERSIONES ANTERIORES
 
            Dim lastRow As Integer = exHoja.Range("A370").End(Excel.XlDirection.xlUp).Row
 
            exHoja.Range("A" & lastRow & ":E" & lastRow).Select()
            exHoja.Range("A" & lastRow & ":E367").Clear()
            exHoja.Range("F1:N367").Select()
            exHoja.Range("F1:N367").Clear()
 
            'ESCRIBIMOS LAS MEDIAS DE CADA COLUMNA
 
            lastRow += 1
 
            exHoja.Cells(lastRow, 1).Select()
            exHoja.Cells(lastRow, 1).Value = "MEDIAS:  "
            exHoja.Cells(lastRow, 1).Font.Color = Color.DarkGreen
            exHoja.Cells(lastRow, 1).Font.Size = 12
            exHoja.Cells(lastRow, 1).Font.Name = "Adobe Garamond Pro Bold"
            exHoja.Cells(lastRow, 1).Interior.Color = Color.Chartreuse
            exHoja.Cells(lastRow, 1).HorizontalAlignment = 3
            exHoja.Cells(lastRow, 2).FormulaLocal = "=REDONDEAR(PROMEDIO(B2:B" & lastRow - 2 & ");2)"
            exHoja.Cells(lastRow, 2).HorizontalAlignment = 3
            exHoja.Cells(lastRow, 3).FormulaLocal = "=REDONDEAR(PROMEDIO(C2:C" & lastRow - 2 & ");2)"
            exHoja.Cells(lastRow, 3).HorizontalAlignment = 3
            exHoja.Cells(lastRow, 4).FormulaLocal = "=REDONDEAR(PROMEDIO(D2:D" & lastRow - 2 & ");0)"
            exHoja.Cells(lastRow, 4).HorizontalAlignment = 3
            exHoja.Cells(lastRow, 5).FormulaLocal = "=REDONDEAR(PROMEDIO(E2:E" & lastRow - 2 & ");0)"
            exHoja.Cells(lastRow, 5).HorizontalAlignment = 3
 
            exHoja.Range("A" & lastRow & ":E" & lastRow).Borders.LineStyle = 1 'BORDES DE LA HOJA
            exHoja.Range("E1").End(Excel.XlDirection.xlDown).Select() 'SELECCIONAMOS LA ÚLTIMA CELDA DE LA COLUMNA E CON DATOS
 
            exLibro.Save()
            exLibro.Close()
            exApp.Quit()
 
            conexion.Close()
 
            ' LIMPIAMOS TODOS LOS PROCESOS DE EXCEL ABIERTOS DE LA MEMORIA
 
            Dim P As System.Diagnostics.Process
 
            Try
 
                For Each P In System.Diagnostics.Process.GetProcesses
 
                    If P.ProcessName.ToUpper Like "*EXCEL*" Then
 
                        P.Kill()
 
                    End If
 
                Next
 
            Catch
 
            End Try
 
            GC.WaitForPendingFinalizers()
            GC.Collect()
 
            conexion.Close()
 
            Dim duracion As TimeSpan = DateTime.Now - comienzo
 
            e.Result = "DURACIÓN: " & duracion.TotalSeconds.ToString() & " SEGUNDOS."
 
    End Sub

1
2
3
4
5
6
7
Sub worker_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
 
        'AQUÍ ACTUALIZAMOS LA BARRA DE PROGRESODE LA OPERACIÓN
 
        pbCalculationProgress.Value = e.ProgressPercentage
 
    End Sub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Sub worker_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
 
        'AQUÍ MOSTRAMOS QUE EL PROCESO ESTÁ ACABADO
 
        Dim Message As String = "OK, HOJA EXCEL ACTUALIZADA CON ÉXITO."
        Dim Caption As String = " ACTUALIZACIÓN "
        Dim Icono As MessageBoxIcon = MessageBoxIcon.Information
        Dim Buttons As MessageBoxButtons = MessageBoxButtons.OK
 
        Dim Resultado As DialogResult
 
        'MOSTRAMOS EL MESSAGEBOX
 
        Resultado = MessageBox.Show(Message, Caption, Buttons, Icono)
 
        pbCalculationProgress.Value = 0
 
    End Sub
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por Giancarlo (488 intervenciones) el 28/10/2021 16:02:24
en el evento work del backgroundworker, debes usar
1
BackgroundData.ReportProgress(2)

además, la propiedad worketReportProgress debe ser true
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por José Vicente (113 intervenciones) el 28/10/2021 17:18:58
Hola, no sé en qué parte del código debo ubicar
1
BackgroundData.ReportProgress(2)
imagino que será en el evento
1
Sub worker_Dowork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
, la otra parte ya la tenía hecha.
Gracias por tu ayuda, espero tus noticias.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por Giancarlo (488 intervenciones) el 29/10/2021 18:12:08
esto debes ponerle dentro del Sub worker_Dowork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)

1
BackgroundData.ReportProgress(2)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por José Vicente (113 intervenciones) el 29/10/2021 18:45:59
Hola, me salta el error: BackgroundData no está declarado.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por Giancarlo (488 intervenciones) el 29/10/2021 22:28:33
BackgroundData era el nombre de mi backgroundworker, debes poner el nombre de tu backgroundworker
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de melqui
Val: 643
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por melqui (242 intervenciones) el 29/10/2021 19:12:05
si bien me parece worker_Dowork, es para que carga en loop esto quiere decir si declaras un camino
1
2
exLibro = exApp.Workbooks.Open("D:\Documentos\Escaneados\Informe_medico_infarto_2019\Tensión\Historico tension.xlsx")
            exHoja = DirectCast(exLibro.Sheets("Histórico tensión " & anio), Excel.Worksheet)

hace que se repita esta funcion infinitas veces, porq no definicion de inicio y final de carga del archivo, ahora si tu lo colocas fuera del dowork
entonces tendras la carga completa en el
1
Dim ds As New DataSet
ai disfribuiyes el total del registro al cargar el dataset

1
dim totallineas  = ds .Tables[0].Select("tabla").Length

1
worker_ProgressChanged.progressbar(totallineas  )

y ese calculo será distribuido en tu
1
worker_ProgressChanged
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de melqui
Val: 643
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por melqui (242 intervenciones) el 29/10/2021 19:14:21
sigue este ejemplo que te va ajudar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Public Partial Class Form1
        Inherits Form
 
        Public Sub New()
            InitializeComponent()
            backgroundWorker1.WorkerReportsProgress = True
            backgroundWorker1.WorkerSupportsCancellation = True
        End Sub
 
        Private Sub startAsyncButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            If backgroundWorker1.IsBusy <> True Then
                backgroundWorker1.RunWorkerAsync()
            End If
        End Sub
 
        Private Sub cancelAsyncButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            If backgroundWorker1.WorkerSupportsCancellation = True Then
                backgroundWorker1.CancelAsync()
            End If
        End Sub
 
        Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
            Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker)
 
            For i As Integer = 1 To 10
 
                If worker.CancellationPending = True Then
                    e.Cancel = True
                    Exit For
                Else
                    System.Threading.Thread.Sleep(500)
                    worker.ReportProgress(i * 10)
                End If
            Next
        End Sub
 
        Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
            resultLabel.Text = (e.ProgressPercentage.ToString() & "%")
        End Sub
 
        Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
            If e.Cancelled = True Then
                resultLabel.Text = "Canceled!"
            ElseIf e.[Error] IsNot Nothing Then
                resultLabel.Text = "Error: " & e.[Error].Message
            Else
                resultLabel.Text = "Done!"
            End If
        End Sub
    End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

Problema con BackGroundWorker

Publicado por José Vicente (113 intervenciones) el 29/10/2021 20:23:03
Hola, lo estoy probando pero no me funciona. No sé por donde tirar.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar