VBA - Define string to worksheet.name without reference - excel

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

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.

Is there a way to dynamically change or specify the location of an excel file in Workbook.Open?

I wrote code to pull information from another workbook and copy it into my active workbook.
sub copydata
Workbooks.Open "C:\User\abc.xlsx"
'test.xlsx is the active workbook, and abc.xlsx is the workbook data is being copied from
Workbooks("abc.xlsx").Worsheets("Sheet1").Range("A1:A10"). Copy
Workbooks("test.xlsx").Worsheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
Workbooks("abc.xlsx").Close SaveChange:=True
End Sub
If this Excel sheet runs the macro on another computer the directory is going to be different and also the file name will have to remain the same.
Is there a way to dynamically change this, or set this when the macro is launched via a button?
I believe it works this way but I didn't test it.
you can dim variables to take the place of the string you are using.
dim path as string
path = (wherever you are pulling the path string data from)
Workbooks(path).Worksheets("Sheet1").Range("A1:A10").Copy
you can actually do this for any of the parts in quotation marks. just dim the variable and populate it with a value
dim sheet as sheets
dim range1 as range
range1 = range("A1:A10")
sheet = worksheets("Sheet1")
should allow you to have all of the parts as variables. so the following code would work
Workbooks(path).Worksheets(sheet).range(range1).copy
ThisWorkbook.path may be very useful to you. hopefully this makes sense what i'm doing because the code isn't complete enough to test from.
Dim Path1 as string
Dim Path2 as string
Dim Answer as boolean
Path1 = "Old"
Path2 = "New"
if Answer = true then
workbooks(ThisWorkbook.Path &"\" & Path1 & "\Newfile.xlsm")
else
workbooks(ThisWorkbook.Path &"\" & Path2 & "\Newfile.xlsm")
end if
this example based on the value of "Answer" will save the file to one path or another.

VBA subscript out of range, code 9

I'm conducting my very first VBA macro and I'm having some difficulties with this seemingly easy code to read data from a closed workbook into my currently opened one.
Sub KAuto()
Dim path As String
path = "C:\files\Utfall.xlsx"
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim openWb As Workbook
Set openWb = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWb.Sheets("March")
currentWb.Sheets("Indata").Range("A1").Value = openWs.Range("A3").Value
End Sub
The problem I'm having is that I get a code 9, subscript out of range. But I've checked that A1 and A3 is existent for the current workbook and the imported one respectively.
What I have tried to do is to omit the ".Value" in all combinations, as that was what the original author did.
Googling this problem I've encountered that people misused functions which I do not use, for instance windows(), or omitted "" for referencing the worksheets, or simply misspelled things. I don't Think I have any of these, and so I need further help.
How can I correct my subscript out of range? Is there a better way to achieve this copying of cells? In the future I want to import 10 files, will this then be obsolete? (I recall someone posting something in the lines of openWb = [file1,file2,file3] and looping through them, but I cannot find it; does anyone have a link?
EDIT: I've copied the path to the file from its properties, so it ought to be correct.
EDIT2:
currentWb.Sheets("Indata").Range("A1").Value = openWs.Range("A3").Value
snippet gives the error
EDIT3: VB editor print screen:
Try using ActiveWorkbook instead of ThisWorkbook.
Set currentWb = ActiveWorkbook
ThisWorkbook refers to the workbook in which the code resides. ActiveWorkbook refers to the workbook that is currently active i.e. "on top" in the Excel application. It looks like your case, the code resides in a different workbook; so what you want is ActiveWorkbook.
And you can ommit the .value from last line.
currentWb.Sheets("Indata").Range("A1") = openWs.Range("A3")
Your code worked fine for me, that`s why I cannot be sure if it will help. There can be an issue, when opening the openWs. The error line can be evaluated before the openWs is actually open. Then maybe add a line :
Application.Wait (Now + TimeValue("00:00:03")) 'this is 3 seconds from now
after the Set openWb = Workbooks.Open(path).

Setting an Active Cell Value to a variable in VBA

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 +

Get Excel sheet name and use as variable in macro

I'm trying to find a way to use an Excel sheetname as a variable in a macro that I've written. Every month I deal with a workbook that is sent to me with 2 sheets. Part of the macro uses the 'Open File' interface to navigate to the folder and open the file.
The first sheet in the file is called 'Report', which is static. All I do with that is delete it (because I don't need it).
The second sheet could be called anything and that's the sheet upon which I need to run the macro. Is there a way to say:
shtName = %whatever_the_sheetname_is_called%
and then use the 'shtName' variable throughout the macro? I suppose getting this new filename as a variable would help as well.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum) etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Resources