PDA

View Full Version : [SOLVED:] Saving index to a variable prior to closing the file



Decatron
07-11-2023, 10:02 AM
Dim x As Long

Sub savefile()
Dim rng As Range, c As Long
Set rng = Sheet2.Range("A2:A8")
c = rng.Cells.Count
If x = c Then
x = 1
Else
x = x + 1
End If
Range("D10") = rng(x)
End Sub

This program code prints the subsequent value from a list of items each time the macro runs. However, it does not save the index of the last value to 'x' before closing the file. Therefore, 'x' starts from the first item on the list on running the macro upon reopening the file. Please suggest a way to save the index of the last list item to the variable 'x' that was inserted using the macro, so that on reopening of the file, the list continues from where it had been left.

For example, suppose ten items from the list were inserted using the macro before closing the file. On running the macro upon reopening of the file, the eleventh item has be inserted and so on.

p45cal
07-11-2023, 12:37 PM
You could lookup the current value of D10 in rng:
Sub savefile()
Dim rng As Range, c As Long, x
Set rng = Sheet2.Range("A2:A8")
c = rng.Cells.Count
x = Application.Match(Range("D10").Value, rng, 0)
If IsError(x) Then x = 0
If x = c Then
x = 1
Else
x = x + 1
End If
Range("D10") = rng(x)
End Sub
and don't need to Dim x outside the macro (use a simple Dim x, not Dim x As Long).

Another, save the value of x in a Name, say "myX". This will be saved with the file:
Sub savefile2()
Dim rng As Range, c As Long, x
Set rng = Sheet2.Range("A2:A8")
c = rng.Cells.Count
x = [myX] 'retrieve value.
If IsError(x) Then x = 0
If x = c Then
x = 1
Else
x = x + 1
End If
ActiveWorkbook.Names.Add Name:="myX", RefersTo:=x
Range("D10") = rng(x)
End Sub


or, of course, save the value of x in a cell somewhere.

Decatron
07-12-2023, 01:36 PM
You could lookup the current value of D10 in rng:
Sub savefile()
Dim rng As Range, c As Long, x
Set rng = Sheet2.Range("A2:A8")
c = rng.Cells.Count
x = Application.Match(Range("D10").Value, rng, 0)
If IsError(x) Then x = 0
If x = c Then
x = 1
Else
x = x + 1
End If
Range("D10") = rng(x)
End Sub
and don't need to Dim x outside the macro (use a simple Dim x, not Dim x As Long).

Another, save the value of x in a Name, say "myX". This will be saved with the file:
Sub savefile2()
Dim rng As Range, c As Long, x
Set rng = Sheet2.Range("A2:A8")
c = rng.Cells.Count
x = [myX] 'retrieve value.
If IsError(x) Then x = 0
If x = c Then
x = 1
Else
x = x + 1
End If
ActiveWorkbook.Names.Add Name:="myX", RefersTo:=x
Range("D10") = rng(x)
End Sub


or, of course, save the value of x in a cell somewhere.

Your assistance is appreciated. Thanks