
CELLS, RANGE y SHEETS dan error dentro de función VBA
Publicado por Federico (2 intervenciones) el 30/03/2018 03:19:40
Quiero escribir un resultado en una celda desde una función VBA. Si coloco una de las tres instrucciones CELL, RANGE o SHEETS en el código VBA el resultado es #¡VALOR! en la celda que llama la función. La fonción trabaja bien y puede exprsar el valor it (# iteración) a través de un MsgBox.
El código es el siguiente:
Valores de prueba Function Preciofin
P = 1175
inc = 0.001
tol = 0.0005
rd = 10
Resultados cuando no se usan las funciones mencionadas:
Preciofin = 1181.82
iteraciones = 6820
El código es el siguiente:
Valores de prueba Function Preciofin
P = 1175
inc = 0.001
tol = 0.0005
rd = 10
Resultados cuando no se usan las funciones mencionadas:
Preciofin = 1181.82
iteraciones = 6820
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
' ***** inicio de instrucciones VBA Modulo1
Public it As Integer
Function truncarn(x As Double, n As Integer) As Double
truncarn = Int(x * ((10) ^ n)) / ((10) ^ n)
End Function
Function Preciofin(P As Double, inc As Double, tol As Double, rd As Integer) As Double
Dim pnuevo, Dif, precioi As Double
'Dim it As Integer
it = 0
precioi = P
Do
it = it + 1
Preciofin = precioi - truncarn(precioi - truncarn(precioi * 1.1 / rd, 0) * rd / 1.1, 2)
If Preciofin <= P Then
pnuevo = precioi + inc
Else
pnuevo = precioi
End If
If pnuevo - precioi <= tol Then
Dif = 0
Else
Dif = pnuevo - precioi
End If
precioi = pnuevo
If it > 10000 Then
Dif = 0
End If
Loop Until Dif = 0
Preciofin = Round(Preciofin, 2)
'Sheets("Metodoit").[H7].Formula = it
'Range("H7").Value = it
' La siguiente instrucción genera un error #¡VALOR! en
' la celda donde se invoca la función, en este caso H5
Cells(7, 8).Value = it
'El siguientes Msgbox da un resultado correcto cuando
'no se activan las celdas con instrucciones Sheets, Range o Cells
MsgBox "iteraciones = " & it
' *** fin de instrucciones VBS Modulo1
End Function
- Precio-iterativo.zip(13,2 KB)
Valora esta pregunta


0