Pregunta de complementos de VBA
-
27-10-2019 - |
Pregunta
Tengo un problema con un complemento VBA en Excel 2010.
He creado algún código para analizar mis datos de Excel. que hice en un complemento.
Sin embargo, cuando cargo el complemento y la ejecución, se produce un error.
El mensaje de error dice: runtime error 91 object variable or With block variable not set
El error apunta a rowSize = ActiveSheet.Rows.Count
.
¿Alguien sabe cómo corregir este error?
Aquí está el código,
Private Sub Workbook_Open()
Dim counter As Long
Dim rowSize As Long
Dim userId As String
Dim answers As String
Dim vals As String
Dim i As Integer
rowSize = ActiveSheet.Rows.Count
counter = 1
'Create Column
ActiveSheet.Cells(1, 7).Value = "Country"
ActiveSheet.Cells(1, 8).Value = "State"
ActiveSheet.Cells(1, 9).Value = "Age"
ActiveSheet.Cells(1, 7).Font.Bold = True
ActiveSheet.Cells(1, 8).Font.Bold = True
ActiveSheet.Cells(1, 9).Font.Bold = True
ActiveSheet.Cells(1, 7).HorizontalAlignment = xlCenter
ActiveSheet.Cells(1, 8).HorizontalAlignment = xlCenter
ActiveSheet.Cells(1, 9).HorizontalAlignment = xlCenter
ActiveSheet.Cells(1, 7).Borders().LineStyle = xlContinuous
ActiveSheet.Cells(1, 8).Borders().LineStyle = xlContinuous
ActiveSheet.Cells(1, 9).Borders().LineStyle = xlContinuous
'Set Value
Do While counter < rowSize
If ActiveSheet.Cells(counter, 1).Value = Null Then Exit Do
If ActiveSheet.Cells(counter, 4).Value = "3" Then
userId = ActiveSheet.Cells(counter, 2).Value
vals = ActiveSheet.Cells(counter, 6).Value
'MsgBox (vals)
temp = Split(vals, ",")
i = 0
Do While i < 10
targetCell = counter + i
If ActiveSheet.Cells(targetCell, 2).Value = userId Then
ActiveSheet.Cells(targetCell, 7).Value = temp(0)
ActiveSheet.Cells(targetCell, 8).Value = temp(1)
ActiveSheet.Cells(targetCell, 9).Value = temp(2)
ActiveSheet.Cells(targetCell, 7).HorizontalAlignment = xlCenter
ActiveSheet.Cells(targetCell, 8).HorizontalAlignment = xlCenter
ActiveSheet.Cells(targetCell, 9).HorizontalAlignment = xlCenter
ActiveSheet.Cells(targetCell, 7).Borders().LineStyle = xlContinuous
ActiveSheet.Cells(targetCell, 8).Borders().LineStyle = xlContinuous
ActiveSheet.Cells(targetCell, 9).Borders().LineStyle = xlContinuous
End If
i = i + 1
Loop
temp = Null
'parsing_question_1(vals, userId)
End If
counter = counter + 1
Loop
End Sub
¡Gracias!
Solución
Un complemento es solo código, sin interfaz de usuario. Como no hay interfaz de usuario, técnicamente no hay una hoja en el archivo adicional que sea la hoja de activos. En realidad, hay hojas en un complemento, pero ninguno de ellos puede ser "activo".
Si desea trabajar con la hoja de trabajo dentro del complemento, debe hacer referencia a esas hojas de una manera diferente. Por ejemplo, si desea trabajar con la primera hoja en su complemento, puede usar código como
Me.Sheets(1).Rows.Count
La palabra clave ME se refiere a la clase en la que se encuentra. En este caso, está en el módulo de THEWKBOOK del complemento, por lo que yo refiere el objeto de libro de trabajo que es el complemento.
Si desea trabajar en una hoja en particular que no está en su complemento, puede abrir ese libro de trabajo en su evento abierto y consultar esa hoja. Como
Dim sh As Worksheet
Set sh = Workbooks.Open("C:\MyPath\MyBook.xls").Sheets(1)
rowSize = sh.Rows.Count
Finalmente, si desea ejecutar código cada vez que se abra algún libro de trabajo, debe crear un módulo de clase personalizado que escuche los eventos de nivel de aplicación. Primero cree un módulo de clase personalizado Cappevents. En ese módulo de clase personalizado, coloque este código
Private WithEvents mApp As Application
Public Property Set App(oApp As Application)
Set mApp = oApp
End Property
Public Property Get App() As Application
Set App = mApp
End Property
Private Sub mApp_WorkbookOpen(ByVal wb As Workbook)
FormatWorkbook wb
End Sub
'or to limit which workbook it runs on - in this example based on the path
'but you may use some other condition like the existence of a particular
'custom document property
Private Sub mApp_WorkbookOpen(ByVal wb As Workbook)
If wb.Path = "\\Server1\mypath" Then
FormatWorkbook wb
End If
End Sub
En un módulo estándar, coloque este código
Public clsAppEvents As CAppEvents
Sub Auto_Open()
Set clsAppEvents = New CAppEvents
Set clsAppEvents.App = Application
End Sub
Sub FormatWorkbook(wb As Workbook)
Dim sh As Worksheet
Set sh = wb.Sheets(1)
'do stuff here
End Sub
Otros consejos
Porque el Woorkbook_Open
Evento de la suma se ejecuta antes de que se abra la primera hoja visible, no hay una hoja activa en ese momento, por lo tanto, ActiveSheet
no está configurado
Como dijo Tim, probablemente no quiera este código en el evento de todos los tiempos de todos modos
Aquí está un enlace que muestra cómo hacer eventos de aplicación