i m new to vba and try to write some code copying some group data from a protected workbook to new Workbook.
In my source sheet is a list of grouped data with some columns like COUNTRY, REVENUE, WIN, LOSS.
The entity of country is grouped by region.
So under ever country is variable number of regions with subRevenue, subWIN, subLOSS.
What I expect: for a defined group of country entities (eg. GERMANY and JAPAN) I want to copy these data with its subdata (regions) to new Workbook.
May anyone provide me a generic example or useful functions?
Thank you in advance! (a VBA Noob)
So here something to start you off with.
First since the sheet is protected you'll need to unprotect it before being able to copy anything. The below code shows you how to do that and uses strPassword as a variable containing the password. Since the sheet is already protected in your case you'd start with unprotecting it, then doing your copying operation and then protecting it again.
In General you can use range.copy with range.pastespecial to copy data wherever you wish. To copy to a new workbook you can use Workbooks.add otherwise just specificy the filepath of the other workbook
Sub YourSub()
Dim ws As Worksheet: Set ws =Worksheets("YourSheet")
Dim strPassword As String: strPassword = "YourPassword"
Set NewBook = Workbooks.Add ' OR the workbook path
ws.Unprotect Password:= strPassword
ws.Range("A1:AA100").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs FileName:= ' Insert FilePath/ FileName here
ws.Protect Password:= strPassword
End Sub
This is some general information about how you would be going about copying ranges from a protected workbook to another workbook. To do this for certain countries you could create a table or use named ranges(using name manager or in VBA itself). Then you can adress the specific ranges either using if.. elseif.. else.. end if or the select case method, with your list of cases pointing towards a range containing all the countries to be copied.
Hope this was helpful as a quick overview
Related
I need help on declaring 2 workbooks globally where the workbook name is based on a cell value.
I have 3 workbooks workbook
"UPSHI" (file name does not change) workbook
"UAH DR_M04 2022"(M04 and 2022 changes monthly depending in month & year) workbook
"2022_M04_OP21_AAH"(2022, M04 & OP21 changes monthly).
UPASHI workbook will be my main file which will create all my buttons and formulas, I created formula in cell B1 for the 2nd workbook that will identify the current name of the 2nd workbook and another formula in cell B7 to identify current name of my 3rd workbook.
I used cell B1 & B7 to activate the workbooks which work fine but I cannot make it work when i want to copy a sheet from workbook 2 to my workbook 3.
I wanted to declare a global variable for each workbook that I can just call when I want to activate or select the work book, how can I make it work?.
Here is my current code:
Sub PrepFile_Click()
Workbooks(ActiveSheet.Range("b1").Value).Activate
Application.DisplayAlerts = False
Sheets("Upstream Asset Hierarchy -OLD").Delete
Application.DisplayAlerts = True
Sheets("Upstream Asset Hierarchy Viewer").Name = "Upstream Asset Hierarchy -OLD"
Workbooks("UPASHI Automation File").Activate
Workbooks(ActiveSheet.Range("b7").Value).Activate
Sheets("Upstream Asset Hierarchy Viewer").Copy before:=Workbooks(ActiveSheet.Range("b1").Value).Sheets("UPSASSET")
End Sub
Try the next way, please:
Declare four Public variables on top of a standard module (in the declarations area):
Option Explicit
Public wbUPS as Workbook, wbUAH as Workbook, wb3 As Workbook, ws As Worksheet
Create a Sub, let us say "SetWorbooks", placing the next code:
Sub SetWorbooks
Set wbUPS = ThisWorkbook
Set ws = wbUPS.Worksheets("The name of the active sheet")
Set wbUAH = Workbooks(ws.Range("b1").Value)
Set wb3 = Workbooks(ws.Range("b7").Value)
End Sub
Run the above code (once) and then just using wbUPS, wbUAH, wb3. Of course, the involved workbooks must be open...
Use the above variables in the next way:
Sub PrepFile_Click()
If wbUAH Is Nothing Then SetWorbooks 'just in case
Application.DisplayAlerts = False
wbUAH.Sheets("Upstream Asset Hierarchy -OLD").Delete
Application.DisplayAlerts = True
wbUAH.Sheets("Upstream Asset Hierarchy Viewer").Name = "Upstream Asset Hierarchy -OLD"
wb3.Sheets("Upstream Asset Hierarchy Viewer").Copy before:=wbUAH.Sheets("UPSASSET")
End Sub
Activation, selection do not bring any benefit (if you know how to avoid that), only consume Excel resources...
If something unclear, please do not hesitate to ask for clarifications. Of course, I couldn't test the above solution.
I'm really new at VBA and have learned what I know so far from internet searches, but I cannot find a resolution to my issue.
I have two workbooks, one with information on all of my company's current projects and another with just the active projects. The Active Projects workbook is where we store all the documents that need reviewing for each project. Each project has it's own worksheet.
When I create a new worksheet in the Active Projects workbook, I would like to use a macro to fill in the relevant project information from the All Projects Workbook.
I have seen code that copies cells and ranges from one workbook to another, but they have the sheet names hard coded in. Like this:
'Copy range to in selected row to clipboard
Workbooks("All Project.xlsx").Worksheets("All Open").Range("B" & (ActiveCell.Row)).Copy
'PasteSpecial to paste values, formulas, formats, etc.
Workbooks("Active Projects.xlsm").Worksheets(InputBoxValue).Range("A2").PasteSpecial Paste:=xlPasteValues
I thought to use an input box to ask for the worksheet name where the copied data would be pasted, but after hours of research, I cannot find out to use the result of the input box for the worksheet name.
Thank you for furthering my VBA education
FYI - this is at high risk of someone putting in the wrong sheet name given the nature of free-form text. That is something you will need to handle on your end so I suggest you look up:
How to check if a sheet given name exists on a book
How to loop a InputBox until an acceptable input is given
Dim Sheet_Name As String
'Get Input
Sheet_Name = Application.InputBox("Enter Sheet Name", Type:=2)
'Use Input
MsgBox ThisWorkbook.Sheets(Sheet_Name).Name
Dim InputBoxValue As String
InputBoxValue = InputBox("Enter sheet name")
'PasteSpecial to paste values, formulas, formats, etc.
Workbooks("Active Projects.xlsm").Worksheets(InputBoxValue).Range("A2").PasteSpecial Paste:=xlPasteValues
Below code will rename active sheet :
Sub Rename_Worksheet()
Dim Str As String
Dim Ws As Worksheet
Set Ws = ActiveSheet
Str = InputBox("Please provide new name for Worksheet : " & Ws.Name)
Ws.Name = Str
MsgBox "Worksheet renamed successfully to " & Str
End Sub
I have what it seems a small issue but cannot figure out how to solve.
So, every week I have to make a bunch of pivot tables to summarize raw data that I am getting. I figured, it would be much easier if I create all the tables into a Layout file and then just copy them to the new file and then change the source. And I wrote the following code:
Sub something()
Workbooks.Open Filename:="C:\\\\Layout.xlsx"
With Workbooks("Layout.xlsx")
.Sheets("Pivot").Copy Before:=ActiveWorkbook.Sheets("Main List")
.Close savechanges:=False
End With
End Sub
This code works just fine. The issue comes when I try to paste the code into my personal workbook and then run through VBA directly, rather than copying and pasting it every time.
What I could do is, to change the code from 'Activeworkbook' to the name of my new workbook but its name change every week, because it is based on a date.
I already tried to declare the name of the new workbook as a string and call it through that but that didn't work either.
Any ideas?
I would use workbook objects to keep the two files clear:
Sub something()
Dim wb_from As Workbook, wb_to As Workbook
Set wb_to = ActiveWorkbook
Workbooks.Open Filename:="C:\\\\Layout.xlsx"
Set wb_from = Workbooks("Layout.xlsx")
wb_from.Sheets("Pivot").Copy Before:=wb_to.Sheets("Main List")
wb_from.Close SaveChanges:=False
end sub
I'm trying to create a series of macros to audit some financial models.
The first macro I’m trying to create is one that names the current cell. Why? I want to name the cell, after that I’m going to record a macro to click the “Trace Precedents” and go to the cell that has the relationship.
After that I need to go back to the original cell, thats the named one. That's easy on the go function, but I need to the naming macro working
My recorded code for the naming macro is as follows:
Sub Namer ()
ActiveWorkbook.Names.Add Name:="Name1", RefersToR1C1:="=Workings!R42C6"
ActiveWorkbook.Names("Name1").Comment = ""
End Sub
I have the following problems:
I need to name the current cell on a workbook with a lot of sheets. I’m gonna be moving between sheets but my recorded code has a “fixed” sheet.
How can I fix that? Name the current cell on the current sheet
Something like this should help you ...
Public Sub CreatesNames()
Dim objSheet As Worksheet
For Each objSheet In ThisWorkbook.Worksheets
objSheet.Names.Add Name:="Name1", RefersTo:=objSheet.Range("A1")
Next
End Sub
... something to note, names can be created at the worksheet level or at the workbook level, so, if you're going to be creating the same name across worksheets then you need to use a Worksheet object, not the Workbook object.
So to use the active cell ...
Sheet Level
ActiveSheet.Names.Add Name:="Name1", RefersTo:=ActiveCell
Workbook Level
ActiveWorkbook.Names.Add Name:="Name1", RefersTo:=ActiveCell
I hope that helps.
Good day all:
I'm trying to use a ActiveX command button to copy excel worksheets into another file. Here's the background:
I have excel log sheets that are being filled up every day. The logs have a set criterion (A, B, C, etc.) being run daily. While we still want to keep the logs in a daily file, I want a command button to be able to export to another workbook as a master file (e.g. "A_Masterfile", "B_Masterfile", etc.).
I've tried researching, but all these requirements come from different sites/pages. But since the method they use are so different, I'm having a hard time trying to get all Syntax to fit so that one code can do everything.
As a rundown, here's what I want it to do:
Export active worksheet to another workbook
a) If workbook exists, copy sheet to end of workbook
b) If workbook does not exist, create workbook and copy sheet
Destination workbook is based on a cell (criterion A, B, etc.)
Destination workbook might be in a different folder as source worksheet/workbook
Based on what I'm researching so far, this is what I'm turning up with.
When simply copying, this is what I read, but I could not get it to work.
ActiveSheet.Copy After:=Workbooks("Destination.xlsx").Worksheets(Worksheets.Count)
For Creating New File, this is what I read, but even from the original site, they said the problem was it copies the whole workbook, not just one specific sheet.
ActiveWorkbook.SaveAs "C:\path\Destination.xlsx"
Finally, I read about concatenation to create "Destination" file name based on a cell value. However, I got so lost with all the syntax. I tried simply copy pasting but I couldn't get it to work.
This is quite a bit to ask. Thanks so much in advance for all your help!
Please let me know if I can clarify anything.
P.S. Extra note: I've done some QBasic and MATLAB and a tiny bit of JAVA programming in school, so I got the logic part down. But I am quite new to VBA syntax, so extra information would be appreciated. :)
Update:
I just learned about "Record Macro" and I tried using it
I got this from it and it works:
Sheets("SourceSheet").Select
ActiveSheet.CheckBoxes.Add(639, 30, 58.8, 16.8).Select
ActiveSheet.CheckBoxes.Add(639.6, 44.4, 58.8, 16.8).Select
ActiveSheet.CheckBoxes.Add(639.6, 61.2, 58.8, 16.8).Select
ActiveSheet.OptionButtons.Add(1279.8, 37.8, 20.4, 18).Select
ActiveSheet.OptionButtons.Add(1280.4, 57, 21.6, 17.4).Select
Sheets("SourceSheet").Copy After:=Workbooks("DestinationMasterFile.xlsx").Sheets(1)
Windows("SourceWorkBook.xlsm").Activate
It works, but only put it after the first sheet instead of putting it in the end. I know it comes from the .Sheets(1), but I don't know how to write it otherwise. Thanks.
I have done a lot more research and trial and error, and I came up with a working code. This might be messy, but it works. Any further improvements are appreciated.
Private Sub CommandButton1_Click()
'Code for Locking
Sheets("W").Unprotect
Range("A1:BZ125").Locked = True
Sheets("W").Protect Password:="hello"
'Code for Copying
'Declarations
Dim Wk As Workbook
Dim FName As String
Dim FNameTwo As String
Dim FilePath As String
Dim TestStr As String
Dim wb As Workbook
'Initializing Constants
Set wb = ThisWorkbook
FName = "C:\Users\PHReyesDa\Desktop\" & Range("BO1") & ".xlsx"
FNameTwo = Range("BO1") + ".xlsx"
'If statement Setup (if exist)
FilePath = FName
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
'If statement
If TestStr = "" Then
'If not existing, create new file
MsgBox "File didn't exist yet; new file created"
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs Filename:=FName
Application.DisplayAlerts = True
Workbooks(FNameTwo).Close SaveChanges:=True
End If
'Reopens Master File
Workbooks.Open FName
wb.Activate
'Find number of worksheets in destination workbook to worksheet could be copied to end of workbook
Dim Num As Integer
Num = Workbooks(FNameTwo).Worksheets.Count
'Copy source worksheet to (the end of) destination workbook
Sheets("W").Select
Sheets("W").Copy After:=Workbooks(FNameTwo).Worksheets(Num)
'Close and save new workbook, confirmation of successful copy
Workbooks(FNameTwo).Close SaveChanges:=True
MsgBox "Worksheet successfully exported and saved to master file"
End Sub