New to VBA here.
At work I am creating a macro that can compile and format data from a report we get monthly and the file name changes.
Since the name changes, instead of having to go into VBE and changing the name from there, is there a user form I might be able to create that allows me to type in the name of the workbook and it will be able to insert it into the script?
What I have so far:
Sub tester()
Dim wbName As String
wbName = Application.InputBox("What is the workbook name?")
If Right(wbName, 4) <> ".xls" Then wbName = wbName + ".xls"
Set mainWB = Workbooks(wbName)
Dim copyThis As Range, pasteThis As Range
Set copyThis = mainWB.Worksheets(2).Columns("F")
Set pasteThis = Workbooks("VBA Workbook.xlsm").Worksheeets(1).Columns("A")
copyThis.Copy Destination:=pasteThis
End Sub
The workbook name will change month to month.
Alternative solutions are welcomed
Thanks all
Assuming your macro is in Personal.xlsb, and you have the workbook you need to reference as the ActiveWorkbook, you can just do:
Dim mainWB as Workbook
Set mainWB = ActiveWorkbook
Then you'd just use mainWB as the reference, so:
mainWB.Worksheets("Sheet1").Range("A1")
Or if you want the user to input the WB name:
Dim wbName as String
wbName = Application.InputBox("What is the workbook name?")
If right(wbName, 4) <> ".xls" Then wbName = wbName + ".xls"
Set mainWB = Workbooks(wbName)
...
...And you'd probably want to add error handling in the InputBox() case, if the user types a name that isn't correct.
Related
Trying to create a script that will open a directory, select the file and assign the workbook name and worksheet name to variables. When the workbook opens the file, I'm trying to get VBA to assign that file to a variable along with the first worksheet.
Workbook Variable: DataFile_Workbook
Worksheet Variable: DataFile_Sheet
Currently my code is :
Sub OpenWorkbooksAndChangeNames
Workbooks.open("\\datafiles\*.xlsx" <- this opens the file in the directory
Dim wb As Workbook
Dim ws As Worksheet
**Set wb = DataFile_Workbook
Set ws = DataFile_Sheet** <- this is where im trying to assign the workbook name open from line 2 to "DataFile_Workbook" and "DataFile_Sheet" as the first worksheet name.
Set the object when you open it. You will need the know the filename from the wildcard, so use the Dir function for that. Note the Dir function returns only a filename and not a path for it.
Dim wb As Workbook
Dim ws As Worksheet
Dim sFilename As String
sFilename = Dir("\\datafiles\*.xlsx")
Set wb = Workbooks.Open("\\datafiles\" & sFilename)
Set ws = wb.Worksheets(1)
'assign them to variables (given your example, there is no need to do this)
Dim DataFile_Workbook As String
DataFile_Workbook = wb.Name
Dim DataFile_Sheet As String
DataFile_Sheet = ws.Name
' show the names
MsgBox DataFile_Workbook ' or just use wb.Name
MsgBox DataFile_Sheet ' or just use ws.Name
Understand that if there is more than one file in that folder that matches the wildcard, it will just open the first one it finds no matter how many there are.
If you know the filename....
Set wb = Workbooks.Open("\\datafiles\" & DataFile_Workbook)
Is there a way to specify a workbook for a sheet without having the full name?
For example, If the workbook name is MyWorbook2015 and the 2015 may change to 2016 in the future, I need to to recognize the workbook based on MyWorkbook, and ignore the 2015. Something similar to this:
With Workbooks("MyWorkbook2015").Sheets("My_Sheet_Name_That_Does_Not_Change")
'do something
End With
In the code sample above, I need it to recognize the work book regardless of the date? Is this possible? If it is, how would I go about doing that?
Yes you can use the LIKE Operator with a wildcard "*". Here is an example. I am assuming that the workbook is open.
Sub Sample()
Dim wb As Workbook
Dim wbName As String
'~~> "MyWorkbook2015"
wbName = "MyWorkbook"
For Each wb In Application.Workbooks
If wb.Name Like wbName & "*" Then
Debug.Print wb.Name
With wb.Sheets("My_Sheet_Name_That_Does_Not_Change")
'~~> Do something
End With
End If
Next wb
End Sub
EDIT
Here is a way where you can use it as a function
Dim wbName As String
Sub Sample()
'~~> "MyWorkbook2015"
wbName = "MyWorkbook"
If Not GetWB Is Nothing Then
Debug.Print GetWB.Name
With GetWB.Sheets("My_Sheet_Name_That_Does_Not_Change")
'~~> Do something
End With
Else
MsgBox "No workbook with that name found"
End If
End Sub
Function GetWB() As Workbook
Dim wb As Workbook
For Each wb In Application.Workbooks
If wb.Name Like wbName & "*" Then
Set GetWB = wb
Exit Function
End If
Next wb
End Function
A slightly more reliable alternative to doing a partial match on Workbook.Name is to do an equivalency match on WorkBook.CodeName. The default CodeName for a Workbook is "ThisWorkbook", but you can change that by selecting the "ThisWorkbook" code page in the Project Explorer window and then open the Properties Window (Key: F4) and change the Name property for the code page.
Then following the example that Siddharth has shown but redefining then "GetWB" function like this:
Function GetWB() As Excel.Workbook
Const wbCodeName As String = "MySecretWorkbookName" ' change to the CodeName you choose
Dim wb As Workbook
For Each wb In Application.Workbooks
If wb.CodeName = wbCodeName Then
Set FindWorkbook = wb
Exit For
End If
Next wb
End Function
Note that changing the CodeName allows you to use the new CodeName in places where you would have used "ThisWorkbook", but you can still use "ThisWorkbook" as well.
I am trying to create a macro that will copy a range from one open sheet (Original.xlsx) to another open sheet (Destination.xlsx). The tricky part is I want the user to be able to name the origin excel filename (without the .xlsx at the end) via inputbox and I am having trouble with combining the dim with the copy function.
Dim wbdest As Workbook
Dim X As Variant
X = InputBox("Workbook from name?")
Set wbdest = Workbooks(X & ".xlsx")
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Workbooks("destination.xlsx").Worksheets("Sheet1").Range("A2").PasteSpecial Paste:=xlPasteValues
The input box in this example will be input with "Original"
I am getting a Runtime error 9, subscript out of range on
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Replace:
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
with:
wbdest.Worksheets("Sheet1").Range("A2:K25").copy
(there may be other errors in your posted code)
Your be best of doing it like this;
Sub test()
Dim wb1 As Workbook 'declare the workbook
Dim wb2 As Workbook 'declare the workbook
Dim strFile As String
strFile = InputBox("Workbook from name?") 'open up input box for user to type in what workbook they want to copy
Set wb1 = Workbooks(strFile & ".xlsx") 'set the user defined workbook by name
Set wb2 = Workbooks("Destination.xlsx") 'set the destination workbook by name
wb2.Worksheets("Sheet1").Range("A2:K25").Value = wb1.Worksheets("Sheet1").Range("A2:K25").Value 'put the value from userdefined workbook into destination
End Sub
Try and avoid copy and pasting if you can :)
I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub
What I need is a way to send the contents of some cells in "ThisWorkbook" (where the macro is) to a specific sheet in another workbook (the location of which will not change, unlike "ThisWorkbook")
for some reason, this below dosen't work:
Sub Transplant()
Dim thispath As String
Dim targetpath As String
'Set filepaths
thispath = ThisWorkbook.FullName
targetpath = ThisWorkbook.Path & "/subdir/Targetbook.xlsm"
Dim Srcwb As Workbook
Dim Trgwb As Workbook
'Set workbooks
Set Srcwb = Workbooks.Open(thispath)
Set Trgwb = Workbooks.Open(targetpath)
Srcwb.Worksheets("Sheet1").Range(Srcwb .Worksheets("Sheet1").Range("A1"), _
Srcwb.Worksheets("Sheet1").Range("A1").End(xlToRight)).Copy _
Destination:=Trgwb.Sheets("Sheet1").Cells(1, 1)
End Sub
Please help!
//Leo
This is pretty much the same as what you've got, although I didnt re-open the active workbook.
Can you describe the range you're trying to copy? You might find that UsedRange is easier.
Sub Transplant()
Dim DWB As Workbook
Dim S As Worksheet
Set S = ThisWorkbook.WorksheetS("Sheet1") ' forgot to rename Source to S
Set DWB = Application.Workbooks.Open(Thisworkbook.Path & "/subdir/Targetbook.xlsm")
Set D = DWB.Worksheets("Sheet1")
S.Range(S.Range("A1"), S.Range("A1").End(xlToRight)).Copy Destination:=D.Cells(1,1)
' S.UsedRange.Copy Destination:=D.Cells(1,1) - this might be easier
End Sub