Setting an Active Cell Value to a variable in VBA - excel

I am trying to run a macro that will open a workbook, complete a series of procedures on it, save it, Close it. Then in the Macro workbook it will move down one row and use that cells value as the filename to open the next workbook.
The issue I am having is how do I get VBA to store a cells value as a variable:
The basics of the macro would look like this:
Dim Num as Long
Num = ActiveSheet.UsedRange.Rows.Count
Dim Name as String
Name = ?
Workbooks.Open Filename:="N:\PricingAudit\FY16 Price Increase\Raw DBF Files\TreatmentFiles\" + Name
...
...
Workbooks(Name).Close
...
Any help would be greatly. Appreciated in this:
Thanks in advance

Say in the worksheet we have:
Then here is one method:
Sub Dural()
Dim MyName As String
MyName = Range("A1").Text
Workbooks.Open Filename:="C:\TestFolder\" & MyName
Set wbfirst = ActiveWorkbook
'.......
'.......
'.......
wbfirst.Close
End Sub
NOTE:
the string variable does not replicate a known property (Name)
we close using an Object rather than "by name"
we use & rather than +

Related

How to create a dynamic VBA code in Excel so that it always refers to a workbook with a changing name?

I want to create a macro where it will copy some data from one workbook (whose name stays always same - "SameNameWorkbook") and pastes that data in another open workbook whose name is changing everyday (because its name is a date). For example today my workbook which I want to paste the data in is called "11.06.2021".
What I did is I created a =today() formula in the J2 cell in the active workbook (different from the other 2 and named "CurrentWorkbook") and created a variable in VBA for the workbook with changing name:
`Second_workbook = Range("J2").Value`
When I want to have always a reference to the second workbook I wrote this:
`Windows("Second_workbook.xlsx").Activate`
`Range.("A1").Select`
`ActiveSheet.Paste`
Since Second_workbook is a variable linked to the =today() formula which is 11.06.2021 I thought that will put the date before .xlsx. However, this shows an error so my logic is wrong. Since I am more fond of Excel formulas I thought that this logic will work like the indirect function but obviously it doesn't.
So the end result which I want to have is following:
`Windows("11.06.2021.xlsx").Activate`
Tomorrow, then I want to have the following:
`Windows(12.06.2021.xlsx").Activate`
... and so on without me manually changing the name workbook in the macro everyday while I keep all 3 workbooks open of course.
Could you please help me with this issue? I would really appreciate your help.
Date Formatting
You have to format your date:
Format(Date, "dd.mm.yyyy") & ".xlsx"
Format(Range("J2").Value, "dd.mm.yyyy") & ".xlsx"
Date is the equivalent of Excel's TODAY in VBA.
Here's a common scenario (adjust the worksheet names and the ranges):
Option Explicit
Sub CopyToToday()
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
' Attempt to create a reference to the Destination Workbook.
Dim dName As String: dName = Format(Date, "dd.mm.yyyy") & ".xlsx"
On Error Resume Next
Dim dwb As Workbook: Set dwb = Workbooks(dName)
On Error GoTo 0
If dwb Is Nothing Then
MsgBox "Could not create a reference to today's workbook.", _
vbCritical, "Workbook not open"
Exit Sub
End If
' Copy a range from Source Worksheet to Destination Worksheet.
swb.Worksheets("Sheet1").Range("A1:F10").Copy
dwb.Worksheets("Sheet1").Range("A1").PasteSpecial
Application.CutCopyMode = False
'dwb.Save
End Sub
"Second_workbook.xlsx" is a string and will be interpreted as a string, ignoring any variables with the same name.
Variables are written out without quotes, and strings of text have the quotes. Everything within quotes (green text) is taken as a string of text. To combine strings and variables we use the & operand like so:
"string" & variable & "string"
So what you are looking for should be:
Windows(Second_workbook & ".xlsx").Activate
You might want to save the workbook as a variable object instead, to refer to it easier:
Dim wb As Workbook
Set wb = Workbooks(Range("J2") & ".xlsx")
Or if you are using the Second_workbook variable anyway, you can set it like:
Set wb = Workbooks(Second_workbook & ".xlsx")
Remember that this range, just as in your example will be interpreted as ActiveWorkbook.ActiveSheet.Range("J").value unless you specify it. Make sure that this won't cuase problems.
To activate a cell in this workbook, you can use wb.Worksheets(1).Range("A1").Select, for example.

How can I add sheets from an excel file to another?

So I am trying to write a Macro for Excel, that adds 2 worksheets from an excel file to a new one.
Therefore, I try this:
Sub addfile()
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Set sheet1 = Sheets.Add(Type:="C:\Users\Helge\AppData\Roaming\Microsoft\Templates\page1.xltx")
Set sheet2 = Sheets.Add(Type:="C:\Users\Helge\AppData\Roaming\Microsoft\Templates\page2.xltx")
End Sub
When I test it, it imports the first page, but the 2nd page gives me a Runtime error 1004.
Why does this happen?
And is there another way to get 2 sheets from one excel file to another via vba?
Much to my surprise this version of your code actually worked for me.
Sub addfile()
Dim Sheet1 As Worksheet
Dim Sheet2 As Worksheet
Set Sheet1 = Sheets.Add(Type:=Environ("Userprofile") & "\OneDrive\Desktop\Template1.xltx")
Set Sheet2 = Sheets.Add(Type:=Environ("Userprofile") & "\OneDrive\Desktop\Book2.xlsx")
Debug.Print Sheet1.Name, Sheet2.Name
End Sub
The reason for my surprise is that Sheet1 and Sheet2 are the default CodeName for the first and second worksheets in any workbook. Therefore there is a conflict of naming between the Sheet1 in the workbook and the Sheet1 you declare which should come to the surface not later than Debug.Print Sheet1.Name. In fact, it may have. I didn't check which name was printed. But the code didn't crash. Since it crashes on your computer, perhaps you have an older version of Excel. Try to stay clear of variable names that Excel also uses. Or there is something wrong with the path & file name, which is hard to tell in that syntax and therefore kept me fooled for quite some time too.
In fact, I discovered the above only after finding out that my Desktop was on OneDrive and not before I had written the function below which is designed to avoid the use of Sheets.Add. It also has some extras such as being able to specify the sheet to take from the template (you could have one template with 2 or more sheets). You can specify an index number or a sheet name. And the function will give a name to the copy, too, if you specify one.
Private Function AddWorksheet(ByVal Template As String, _
TabId As Variant, _
Optional ByVal TabName As String) As Worksheet
Dim Wb As Workbook
Dim Path As String
Dim FileName As String
Set Wb = ThisWorkbook ' change to suit
' make sure the path ends on "\"
Path = "C:\Users\Helge\AppData\Roaming\Microsoft\Templates\"
With Workbooks.Open(Path & Template)
.Sheets(TabId).Copy After:=Wb.Sheets(Wb.Sheets.Count)
.Close
End With
Set AddWorksheet = ActiveSheet
If Len(TabName) Then ActiveSheet.Name = TabName
End Function
You can call the function from a sub routine like this:-
Sub AddWorksheets()
Dim Tab1 As Worksheet
Dim Tab2 As Worksheet
Application.ScreenUpdating = False
Set Tab1 = AddWorksheet("Page1.xltx", 1, "New Tab")
Set Tab2 = AddWorksheet("Page2.xltx", "Sheet1", "Another new Tab")
Application.ScreenUpdating = True
End Sub
Please observe the difference between the two function calls.

Changing Workbook Reference with VBA

Currently, I have a workbook without VBA, that pulls the maximum value from a specific range on a few different sheets in an external workbook. In the future, I would like to be able to frequently update the source workbook, while the sheet name and cell ranges will always be the same. For example, the following are a few of my current cell formulas:
=MAX(ABS(IF('[Test.xlsx]Page_3'!$B$6:$B$107<$B$8,'[Test.xlsx]Page_3'!$A$6:$A$107)))
=MAX(ABS(IF('[Test.xlsx]Page_4'!$B$6:$B$107<$B$8,'[Test.xlsx]Page_4'!$A$6:$A$107)))
Is there a way that I can define a sheet name, while still using these formulas in the cells? What I am envisioning is something like this:
Private Sub CommandButton1_Click()
Dim path As String
Dim wbk As Workbook
path = Application.GetOpenFilename()
Set wbk = Workbooks.Open(path)
End Sub
then I would be able to use that variable within the cells like this:
=MAX(ABS(IF('[wkb]Page_3'!$B$6:$B$107<$B$8,'[wkb]Page_3'!$A$6:$A$107)))
Is something like this possible? I would like to avoid coding all of my functions within the VBA window. I am much more comfortable with the syntax of the Excel functions.
Try the next code, please:
Sub testOpenWB_Formula()
Dim sh As Worksheet, path As String, wbk As Workbook, shortName As String
Set sh = ActiveSheet 'use here your sheet
path = Application.GetOpenFilename()
Set wbk = Workbooks.Open(path)
shortName = Split(path, "\")(UBound(Split(path, "\")))
sh.Range("A8").Formula = "=MAX(ABS(IF('[" & shortName & "]Page_3'!$B$6:$B$107<$B$8,'[" & _
shortName & "]Page_3'!$A$6:$A$107)))"
sh.Range("A9").Formula = "=MAX(ABS(IF('[" & shortName & "]Page_4'!$B$6:$B$107<$B$8,'[" & _
shortName & "]Page_4'!$A$6:$A$107)))"
End Sub
Take care to change the cells where the formulas to be placed ("A8" and "A9" in my test code).

is there a way i can copy the first characters of an excel filename and paste it in the worksheet?

i want to copy the the first 7 characters of my excel file name into a column in my summary sheet. my file name typically goes something like "PR_0001_nil_officer.xls". i want to copy the "PR_0001" and paste it in column range G2:G6 of my worksheet. Also Im very new to VBA so which makes this seemingly simple task more complex to me lol
Use ThisWorkbook.Name to get the workbook name.
Use the Left function to get the left 7 characters of that name
Write it to the range in your desired worksheet
ThisWorkbook.Worksheet("Summary").Range("G2:G6").Value = Left$(ThisWorkbook.Name, 7)
Option Explicit
Sub Test()
Dim strName As String
Dim wsSummary As Worksheet
With ThisWorkbook
Set wsSummary = .Worksheets("Summary")
strName = Left(.Name, 7)
wsSummary.Range("G2:G6").Value = strName
End With
End Sub

VBA - Define string to worksheet.name without reference

I am new to VBA and got that problem which I don't know how to fix.
I have a workbook with some sheets and I create a new workbook for each sheet in that first one with the name of the sheets. That works...
Now, I declare a variable of type string which defines the path to one of these new workbooks.
After defining that string I use that in the open function and when i change something in that workbook i opened, it also changes it in the worksheet where i get the name from(e.g. the name of the worksheet, like below)
Public Sub ProcessWorksheet(ByVal Worksheet As Excel.Worksheet)
Dim fileName As String
Dim currProFile as Workbook
Dim currProSheet as Worksheet
fileName ="some path" & "\" & worksheet.name & ".xlsx"
Set currProFile = Workbooks.Open(fileName)
Set currProSheet = currProFile.ActiveSheet
currProSheet.name = "DATA"
End Sub
So I think there is a reference to that worksheet i just use for the name cause of that worksheet.name.
My question is: How can I get the name without a reference to the worksheet.
I hope it is all cleal and thanks for help!
Well, I started all over again and just used the most important code and now it works. I don't know why but it does. So I think it was just an error by Excel itself.
Anyways thank you braX for editing advice

Resources