Save variable into a cell to use in a formula

johnnyL

Well-known Member
Joined
Nov 7, 2011
Messages
4,546
Office Version
  1. 2007
Platform
  1. Windows
Need some help here. ;( Hopefully someone here can help.

I have googled many other questions I have had and several of the results lead me to this forum. So I figure this would be a good place to post my question.

I have excel 2007 and I am new to this Excel stuff ... been playing with it for about 1.5 months or so, so I am still a newbie so to speak in Excel.
Here is a brief description of what I am trying to do:

I am working with two workbooks, 'Completed.xlsx' & 'Next.xlsx', for example. What I want to do is have the user select the 'completed.xlsx' workbook, whatever existing workbook they want to choose, and then save that chosen workbook name into a cell into the other open workbook 'Next.xlsx', or whatever they called it.

The checking for existing or already open workbooks is working fine, so that part is not an issue. I can get both workbooks to open, if one or both are not already open, so that is not a problem.

Basically, the only problem I am faced with now, is how to save the workbook chosen ('completed.xlsx') into a cell that is located in the 'Next.xlsx' workbook. The names of the workbooks may change because I am asking the user for the names of both workbooks. So I can't 'hardcode' the name of the workbook into the 'Next.xlsx' workbook cell, for example.
So, in a nutshell, I will ask the user to select two different workbooks, names will vary, and I want to save the name of the first selected workbook into a cell of the second selected workbook, ie. save it as a variable.

I have tried various things, but I believe I have the syntax incorrect and therefor have been unsuccessful thus far in this goal. :( After it is saved into a cell in the second workbook, I want to use that cell value, ie. the first workbook name, to load a cell value from that first workbook name/sheet into the second workbook selected/sheet. Sheet names might vary between the workbooks, but the order of the sheets should be presumed to be in the same order. So basically both workbooks are arranged in the same order sheet wise, as well as the rows and columns.

I think I have explained my intentions, but if there is anything I am being vague about, please let me know, and I will offer up further info.

Any Help would be most appreciated! Thank you!
 
Yep, it was on my end, the wife hid a few rows in the 'next file' here and there, and that was what was throwing off my results. After correcting that, this bit of code seems to work fine.

Tomorrow, I will see if I can encorporate this code into the master file.

Thanks again!
 
Upvote 0

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
...
Tomorrow, I will see if I can encorporate this code into the master file.

Thanks again!

Hmm, I think I need one more kick in the butt if ya don't mind.

After I put the code into my file, it works fine the initial run through with no files open. But, if I run it immediately after that with the files still open, I get an error ... run time error '9' Subscript out of range. It happens on the following line ...

Code:
'***********************************************************************************
Get_Worksheet_Name:
'***********************************************************************************
    [COLOR=red]With Workbooks(Original_Current_Week_File_Name)
[/COLOR]        ' Set up loop to go through first 5 sheets of the workbook
        For Sheet_Counter = 1 To 5
'
            'get corresponding sheet name from Current_Week_File_Name
            Current_Week_Sheet_Name = Workbooks(Current_Week_File_Name) _
                .Sheets(Sheet_Counter).Name

Any ideas? Like I said, it works fine if none of the files are open originally, but if I rerun it immediately afterwards, I get that error.
 
Upvote 0
Johnny,

Most likely variable Original_Current_Week_File_Name isn't assigned a value at this point in your code,
or if it is assigned, it doesn't match an open filename.

We'll need to see more of the code to determine the problem.
Could you post the whole Sub?
 
Upvote 0
Johnny,

Most likely variable Original_Current_Week_File_Name isn't assigned a value at this point in your code,
or if it is assigned, it doesn't match an open filename.

We'll need to see more of the code to determine the problem.
Could you post the whole Sub?

Absolutely!

Code:
Sub Pre_Plan()
'***********************************************************************************
'
' Pre_Plan Macro
' This will ask for the files that are needed to pre plan, and then will pre plan for you
'
' Keyboard Shortcut: Ctrl+g
'
' V1.2
'
'***********************************************************************************
' MsgBox Notes:
'***********************************************************************************
'
' Type of Buttons:          Potential Return Responses:
' 1 vbOKOnly                vbOK
' 2 vbOKCancel              vbOK,       vbCancel
' 3 vbAbortRetryIgnore      vbAbort,    vbRetry,    vbIgnore
' 4 vbYesNoCancel           vbYes,      vbNo,       vbCancel
' 5 vbYesNo                 vbYes,      vbNo
' 6 vbRetryCancel           vbRetry,    vbCancel
'
'***********************************************************************************
'
    Dim Current_Week_File_Name          As String
    Dim DisplayMsg                      As String
    Dim Original_Current_Week_File_Name As String
    Dim SaveToWorkBook                  As String
    Dim Start_Row_of_Data               As Integer
    Dim VerifyRequest                   As Integer
    Dim VerifyRequestHeader             As String
'
'***********************************************************************************
Display_Opening_Prompt:
'***********************************************************************************
'
'   Message Title displayed to viewer
    VerifyRequestHeader = "You are about to Pre-plan the "
    VerifyRequestHeader = VerifyRequestHeader & "'Student/Adult Portions "
    VerifyRequestHeader = VerifyRequestHeader & "Planned' Columns. IE. (E & F)!"
'
'   Additional Message displayed to viewer
    DisplayedMsg = "This will perform your Pre-planning for you, for the entire week."
'
'   Display the Entire MessageBox to the viewer with options
    VerifyRequest = MsgBox(DisplayedMsg, vbOKCancel, VerifyRequestHeader)
'
'   Check which button was pressed
    If VerifyRequest = vbCancel Then            ' If they chose to cancel, then ...
        Exit Sub                                ' Exit Pre-Planning
    End If
'                                               ' Otherwise ....
'***********************************************************************************
Get_Current_Week_File_Name:
'***********************************************************************************
'
'   Show the 'Open' window and pass the selected file name to
'   the String variable named "Current_Week_File_Name"
    Current_Week_File_Name = Application.GetOpenFilename _
        ("Excel Files (*.xl*), *.xl*,All Files(*.*),*.*", 1, _
        "Select Current week file.  !!! FYI !!! Hold 'alt' key and press 'arrow up' key one time to go up one folder")
 
 
'
'   Check if User still wants to continue with request
    If Current_Week_File_Name = "False" Then    ' Request was cancelled
        MsgBox "Cancelled 'Pre Plan' request."  ' Display cancelled message
        Exit Sub                                ' Exit Pre-Planning
    End If
'
'   A 'Copy from' file name/location has been selected.
'
'   Because Windows7 is stupid ...
'   Check to see if the file extention is included in the file name.
'   If it isn't, then add it to the end of the file name.
    If Mid(Current_Week_File_Name, Len(Current_Week_File_Name) - 3, 1) <> "." And _
        Mid(Current_Week_File_Name, Len(Current_Week_File_Name) - 4, 1) <> "." Then
            FileExtention = InputBox(Prompt:="Please enter the file extention type for this file.", _
                Title:="Warning! File extention Missing ... xlsx, txt, zip, etc", _
                Default:="xlsx")
            Current_Week_File_Name = Current_Week_File_Name & "." & FileExtention
    End If
'
'   Test to see if the file to be 'copied from' is already open.
    If IsFileOpen(Current_Week_File_Name) Then      ' If File is already opened then ...
        GoTo Get_Original_Current_Week_File_Name:   ' Go ask user for the original file
    Else                                            ' Else, if File is not open yet ...
'       If we land here, then the file that they want to get 'pre plan' numbers from is not open yet.
        Workbooks.Open (Current_Week_File_Name)     ' Open the file
'
'       Save just the workbook name and extention into Current_Week_File_Name
        Current_Week_File_Name = ActiveWorkbook.Name
   End If
'
'_____________________________________________________________________________________
'***********************************************************************************
Get_Original_Current_Week_File_Name:
'***********************************************************************************
'
'   Show the 'Open' window and pass the selected file name to
'   the String variable named "Original_Current_Week_File_Name"
    Original_Current_Week_File_Name = Application.GetOpenFilename _
        ("Excel Files (*.xl*), *.xl*,All Files(*.*),*.*", 1, _
        "Select Original Current Week File Name.    !!! FYI !!! Hold 'alt' key and press 'arrow up' key one time to go up one folder")
'
'   Check if User still wants to continue with request
    If Original_Current_Week_File_Name = "False" Then   ' Request was cancelled
        MsgBox "Cancelled 'Pre Plan' request."          ' Display cancelled message
        Exit Sub                                        ' Exit Pre-Planning
    End If
'
'   A 'Copy to' file name/location has been selected.
'
'   Because Windows7 is stupid ...
'   Check to see if the file extention is included in the file name.
'   If it isn't, then add it to the end of the file name.
    If Mid(Original_Current_Week_File_Name, Len(Original_Current_Week_File_Name) - 3, 1) <> "." And _
        Mid(Original_Current_Week_File_Name, Len(Original_Current_Week_File_Name) - 4, 1) <> "." Then
            FileExtention = InputBox(Prompt:="Please enter the file extention type for this file.", _
                Title:="Warning! File extention Missing ... xlsx, txt, zip, etc", _
                Default:="xlsx")
            Original_Current_Week_File_Name = Original_Current_Week_File_Name & "." & FileExtention
    End If
'
'   Test to see if the file to be 'copied to' is already open.
    If IsFileOpen(Original_Current_Week_File_Name) Then     ' If File is already opened then ...
        GoTo Get_Worksheet_Name:                            '   continue on to formulas
'
    Else                                                    ' Else, if File is not open yet ...
'       If we land here then the file that they want to put 'pre plan' numbers into is not open yet.
        Workbooks.Open (Original_Current_Week_File_Name)    ' Open the file
'
'       Save just the workbook name and extention into Original_Current_Week_File_Name
        Original_Current_Week_File_Name = ActiveWorkbook.Name
    End If
'
'_____________________________________________________________________________________
'
'   We don't need this anymore because we are gonna use the macro to write the formulas for us.
'
'   Save the file name chosen for the current week file into a cell in our original
'   file chosen so we can use it in our preplanning formulas.
'   With Workbooks(SaveToWorkBook)
'       .Sheets(12).Range("A2") = Current_Week_File_Name
'   End With
 
 
 
'
'***********************************************************************************
Get_Worksheet_Name:
'***********************************************************************************
    With Workbooks(Original_Current_Week_File_Name)
        ' Set up loop to go through first 5 sheets of the workbook
        For Sheet_Counter = 1 To 5
'
            'get corresponding sheet name from Current_Week_File_Name
            Current_Week_Sheet_Name = Workbooks(Current_Week_File_Name) _
                .Sheets(Sheet_Counter).Name
'
'***********************************************************************************
Find_Starting_Row_of_Data:
'***********************************************************************************
            For Each Cell In .Sheets(Sheet_Counter).Range("A1:A60")
'               Check 'A' column for Left part of string = "PLANNING"
                If Left(Cell.Value, 8) = "PLANNING" Then   ' If found then ...
                    Start_Row_of_Data = Cell.Row + 5      '   Our data starts 5 rows down from this
                    GoTo Find_Ending_Row_of_Data:
                End If
            Next Cell                                      ' go check next cell in range for our 'flag'
'
'           Warning !!! Our 'flag' was not found ... Something is not right.
            MsgBox "Could not find the start of the data section. Program terminated!"
            Exit Sub
'
'***********************************************************************************
Find_Ending_Row_of_Data:
'***********************************************************************************
            For Each Cell In .Sheets(Sheet_Counter).Range("A1:A60")
'               Check 'A' column for Left part of string = "Leftover"
                If Left(Cell.Value, 8) = "Leftover" Then   ' If found then ...
                    Ending_Row_of_Data = Cell.Row - 1      '   Our data ends on this line
                    GoTo Write_Formulas
                End If
            Next Cell                                      ' go check next cell in range for our 'flag'
'
'           Warning !!! Our 'flag' was not found ... Something is not right.
            MsgBox "Could not find the end of the data section. Program terminated!"
            Exit Sub
'
'***********************************************************************************
Write_Formulas:
'***********************************************************************************
            For Each Cell In .Sheets(Sheet_Counter).Range("E" & Start_Row_of_Data & ":F" & Ending_Row_of_Data)
                If Cell.HasFormula = False And _
                        WorksheetFunction.IsNumber(Cell.Value) Then
                    Cell.Interior.Color = vbGreen  'use this cell
                    Cell.FormulaR1C1 = _
                        "='[" & Current_Week_File_Name & "]" & _
                          Current_Week_Sheet_Name & "'!" & "RC[12] + " & Cell.Value
                ElseIf Cell.HasFormula = True Then
                    Cell.Interior.Color = vbRed  'skip this cell
                End If
            Next Cell
        Next Sheet_Counter
    End With
 
 
 
'***********************************************************************************
Delete_Formulas_From_Pre_Planning:
'***********************************************************************************
'
'       Save just the workbook name from the entire path name
'        SaveToWorkBook = ExtractFileName(Original_Current_Week_File_Name)
''        SaveToWorkBook = Original_Current_Week_File_Name
'
'       Set it as the active workbook
'       Workbooks("Cycle B Elementary Lunch Production Record.xlsx").Worksheets("Cycle B Day 1").Activate   ' No longer Needed
'        Workbooks(SaveToWorkBook).Worksheets(1).Activate    ' Worksheets(x) = which worksheet
        Workbooks(Original_Current_Week_File_Name).Worksheets(1).Activate    ' Worksheets(x) = which worksheet
'
        Dim Loop_Counter As Integer
'
'       Set up loop to go through all 5 workdays of the week ... first 5 sheets in the workbook
        For Loop_Counter = 1 To 5               ' Sheets.Count  ... would = all sheets ;)
            Sheets(Loop_Counter).Select
'
'           highlight range to delete formulas from
            Range("E13:F50").Select
'
'           Delete formulas from the selected range of cells
            Selection.Copy
                Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Application.CutCopyMode = False
        Next Loop_Counter                   ' Loop back to beginning of this loop until finished
'
        MsgBox "Congratulations!!! Your Pre Planning has been done for you !!!" & vbCr & vbCr & "Now designate where you want to save/Rename this resulting file." & vbCr & vbCr & "Hint: 'pre planning' folder ;)"
'
'       Ask the user where and what to save the file as
        FileSaveName = Application.GetSaveAsFilename( _
        fileFilter:="Microsoft Office Excel Workbook (*.xlsx), *.xlsx")
        If FileSaveName = False Then End
        ActiveWorkbook.SaveAs Filename:=FileSaveName
'    Else                                        ' They chose to cancel
'        Exit Sub                                ' Exit Pre-Planning
'    End If
End Sub
'***********************************************************************************
Function IsFileOpen(FullPathFileName As String) As Boolean
'***********************************************************************************
'
    Dim Filenum As Long
'
'   An Error is generated if you try opening a File for ReadWrite lock
'   when it is already open!
    On Error GoTo FileIsOpen:                   ' If Error occurrs, then file is already open
'
    Filenum = FreeFile                          ' Get a free file number
    Open FullPathFileName For Random Access Read Write _
        Lock Read Write As Filenum
'
'   If we make it to here, then No error occurred, File was not already open
    IsFileOpen = False                          ' Set this function result to 'False'
    Close Filenum                               ' Close the file
    On Error GoTo 0                             ' Turn off Error handling
    Exit Function
'
' If we land here, an error occurred because the file is already open
FileIsOpen:
        IsFileOpen = True                       ' Set this function result to 'True'
        Err.Clear                               ' Clear Error
        Close Filenum                           ' Close the file
        On Error GoTo 0                         ' Turn off Error handling
End Function
 
Upvote 0
:eeek: Wow...you've been busy.

When the user browses to the file and selects it, the variable Original_Current_Week_File_Name includes a full file path.

If the file is closed, then the code opens it and runs this line which strips the path.

Code:
        Original_Current_Week_File_Name = ActiveWorkbook.Name

The problem with your current code is that if the file is already open, you jump using

Code:
GoTo Get_Worksheet_Name:

so it doesn't work when you try to use that reference as:
Code:
With Workbooks(Original_Current_Week_File_Name)
...because it has the full path
 
Upvote 0
:eeek: Wow...you've been busy.

When the user browses to the file and selects it, the variable Original_Current_Week_File_Name includes a full file path.

If the file is closed, then the code opens it and runs this line which strips the path.

Rich (BB code):
        Original_Current_Week_File_Name = ActiveWorkbook.Name

The problem with your current code is that if the file is already open, you jump using

Rich (BB code):
GoTo Get_Worksheet_Name:

so it doesn't work when you try to use that reference as:
Rich (BB code):
With Workbooks(Original_Current_Week_File_Name)
...because it has the full path

Ok I changed the following ...
Code:
'
'   Test to see if the file to be 'copied to' is already open.
    If IsFileOpen(Original_Current_Week_File_Name) Then     ' If File is already opened then ...
        [COLOR=red]Original_Current_Week_File_Name = ActiveWorkbook.Name[/COLOR]
        GoTo Get_Worksheet_Name:                            '   continue on to formulas

But then I get same error different line#:
Code:
Get_Worksheet_Name:
'***********************************************************************************
    With Workbooks(Original_Current_Week_File_Name)
        ' Set up loop to go through first 5 sheets of the workbook
        For Sheet_Counter = 1 To 5
'
            'get corresponding sheet name from Current_Week_File_Name
            [COLOR=red]Current_Week_Sheet_Name = Workbooks(Current_Week_File_Name) _
                .Sheets(Sheet_Counter).Name
[/COLOR]

And Yes, I have been busy trying to learn this language, with much help from you, TY.
 
Upvote 0
Ok I got it, had to add the line to the original part also if it was already opened. :)

Thanks again for all of the help thus far, I am off to testing again.
 
Upvote 0

Forum statistics

Threads
1,226,216
Messages
6,189,675
Members
453,562
Latest member
overmyhead1

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top