My question is as follows:
I have given a workbook to multiple people. They have this workbook in a folder of their choice. The workbook name is the same for all people, but folder locations vary.
Let's assume the common file name is MyData-1.xls.
Now I have updated the workbook and want to give it to these people. However when they receive the new one (let's call it MyData-2.xls) I want specific parts of their data pulled from their file (MyData-1) and automatically put into the new one provided (MyData-2).
The columns and cells to be copied/imported are identical for both workbooks. Let's assume I want to import cell data (values only) from MyData-1.xls, Sheet 1, cells B8 through C25 ... to ... the same location in the MyData-2.xls workbook. How can I specify in code (possibly attached to a macro driven import data now button) that I want this data brought into this new workbook. I have tried it at my own location by opening the two workbooks and using the copy/paste-special with links process. It works really well, but It seems to create a hard link between the two physical workbooks. I changed the name of the source workbook and it still worked. This makes me believe that there is a "hard link" between the tow and that this will not allow me to give the target (MyData-2.xls) workbook to others and have it find their source workbook.
To clarify my understanding, each user has a spreadsheet called MyData-1.xls but with varying locations. You would like to send each person a new spreadsheet MyData-2 which will automatically pull in data from range B8:C25 in MyData-1.xls?
There are various options on doing this and below I have provided one way of doing this. In short, the user will open MyData-2, click a button, and the code will search for MyData-1 on their directory, open the workbook, grab the data, paste it into MyData-2, and then close MyData-1.
Sub UpdateWorkbook()
'Identify workbook you would like to pull data from (same for all users)
Dim TargetWorkbook As String
TargetWorkbook = "MyData-1"
'Get the full path of that workbook by searching in a specified directory
Dim TargetPathName As String
TargetPathName = GetFilePath(TargetWorkbook)
'Retrieve data in range B8:C25, copy and paste, then close workbook
Dim TargetRng As Range
Application.ScreenUpdating = False
Workbooks.Open Filename:=TargetPathName
Set TargetRng = Sheets("Sheet1").Range("B8:C25")
TargetRng.Copy Destination:=ThisWorkbook.Worksheets(1).Range("B8:C25")
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub
Function GetFilePath(TargetWkbook As String) As String
Dim FullFilePath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error Resume Next
With Application.FileSearch
.NewSearch
.LookIn = "C:\"
.FileType = msoFileTypeExcelWorkbooks
.SearchSubFolders = True
.Filename = TargetWkbook
If .Execute > 0 Then
FullFilePath = .FoundFiles(1)
End If
End With
GetFilePath = FullFilePath
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Function
By way of explanation:
In the sub you first need to specify the name of the workbook MyData-1
The Function GetFilePath will then get the full path name of the workbbok. Note that I have set it to look in the "C:\" drive and you may want to amend that
Once we have the full file path we can easily open the workbook and copy the required range.
Note that the screenupdating is turned off to create the 'illusion' that the workbook has not been opened when the data is copied. Also, I have added a button on the worksheet of MyData-2 to trigger the code i.e. user opens workbook, presses button, and data is imported.
Finally, this code could be augmented significantly and you may want to tweak it. For example, error checking if file not found, searching in multiple directories (e.g C:\, D:)...
Hope this gets you started on the right track
You should use the copy/paste-special for values only:
Private Sub ImportData_Click()
On Error GoTo OpenTheSheet
Workbooks("MyData-1.xls").Activate
GoTo SheetOpen
OpenTheSheet:
Workbooks.Open "MyData-1.xls"
Workbooks("MyData-1.xls").Activate
SheetOpen:
On Error GoTo 0
Workbooks("MyData-1.xls").Worksheets("sheetwhatever").firstRange.Copy
Workbooks("MyData-2.xls").Worksheets("anothersheet").yourRange.PasteSpecial(xlPasteValues)
End Sub
This could be cleaned up a bit, but it's always messy to do file stuff in VBA, I'd probably put the opening code in a function.
Make sure they put the new file in the same directory as the old file.
Related
I'm fairly new to vba and i don't understand why i'm getting error 400.
I'm having this list. When i push the button, this list has to be deleted, you have to select a file and then the new list will be copied from this file to the list. The list is always the same amount of columns (A-J), variable in length (rows) so in column K i can put a formula to test some data in the list according to data on another sheet.
The problem is with the vba-line
.Sheets("Blad1").UsedRange.Copy LijstBP.Sheets("Blad1").Range("A1")
To test my code, I used a list on sheet "Blad2". My code works perfect with all lists i'm trying to copy. (ofcourse i had to change the code to "Blad2")
Now, the new lists are on sheet "Blad1". I only changed "Blad2" into "Blad1" and the error occurs...
Someone can spread a light on this? Thanks.
My entire code is:
Sub ImporteerData()
Dim LijstBP As Workbook
Dim Bron As Workbook
Set LijstBP = ActiveWorkbook
Call WisHuidigeLijst
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
Workbooks.Open .SelectedItems(1)
With ActiveWorkbook
.Sheets("Blad1").UsedRange.Copy LijstBP.Sheets("Blad1").Range("A1")
.Close False
End With
End If
End With
'Formule kopiëren
Set LijstBP = ActiveWorkbook
Range("K3").FillDown
End Sub
Private Sub WisHuidigeLijst()
Dim laatsteRij As Integer
laatsteRij = Cells(3, "A").End(xlDown).Row
ActiveSheet.Range("A1").Select
Range("A1:J" & laatsteRij).Value = ""
End Sub
I just solved the problem: My collegue, who makes the lists that i need to import, did something wrong: he created a list from columns A-I instead of A-J. By creating a new list from A-J, the whole thing works. My apologies for bothering with such stupidity :-) Last week, i didn't notice this. Thanks to all for trying to help me. –
I made the code to convert the values to the csv file but the problem is
that I'm not sure if this is the right way because this is the first time I even touched VBA macro! As seen in the image I provided, there is a button "Convert to CSV", when I tap it, the macro will call ExportWorksheetAndSaveAsCSV method and will convert the entire sheets contents into csv. However, it looks like it converts the entire sheet it'self.
What I want to do is the following steps .
1.Pass in the Sheet name as a parameter like ExportWorksheetAndSaveAsCSV("Sheet2"), so that it can be used as a file name. But I'm not sure how I can pass a parameter in function from the Buttton.
2.Convert the values in the columns E to I to CSV. If possible want to have the tites of the data show in the first row of the csv file.
I attached the image and the code so you can see. Some tips or examples will be really helpful! I would love to hear from you.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim book As String
Dim fileName As String
book = "Sheet1"
fileName = "test.csv"
Set shtToExport = ThisWorkbook.Worksheets(book) 'Export to CSV file
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs fileName:="C:\Users\myStuff\Documents\" & fileName, FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
I made a workbook in which some sheets are needed to be protected from watching since a lot of people are going to enter this sheet and I would like to have more sensative information in it which will not be available for all.
To do so I googled and found out the following code:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = "Sheet1"
If ActiveSheet.Name = MySheet Then
ActiveSheet.Visible = False
Response = InputBox("Enter password to view sheet")
If Response = "MyPass" Then
Sheets(MySheet).Visible = True
Application.EnableEvents = False
Sheets(MySheet).Select
Application.EnableEvents = True
End If
End If
Sheets(MySheet).Visible = True
End Sub
which works perfectly for my needs but there is a problem.
The problem is as following, for it to work I need to force the user to enable macro commands and if you were to save the file then you'd have to save it as an macro-enabled workbook which is not something I trust my users to do.
My question is: Can I make so that without enabling the macro command you are unable to open the sheet without accepting the macros and you are unable to save as a normal Excel workbook?
I think the best answer here is password-protecting that worksheet using excel's built in functionality: http://www.excel-easy.com/examples/protect-sheet.html
EDIT: protecting sheet only prevents edits, suggested new method of hiding detailed here: http://www.techrepublic.com/blog/microsoft-office/hide-excel-sheets-really-hide-them/
I have two spreadsheets; I'll call them spreadsheet 1 and spreadsheet 2. Spreadsheet one has a function which generates days of the month, and if it's at the end of the month, it is trying to call the module/sub in spreadsheet 2. This is to generate both "daily" reports and "monthly" reports.
At this point, there are two errors: the first is when I am trying to save the new instance of spreadsheet 2 that I created. The error is that it asks to save the workbook in a macro-free format. I simply want to save it! Not to make any changes to formatting. I am not even sure that it is trying to save changes to the instantiated book object.
the second is in spreadsheet 2, even though I set it to be active sheet (I think), the activesheet still comes up as the worksheet on spreadsheet 1 that runs the macro in the first place.
Any help is appreciated.
Option Explicit
Public Function LastWeekOfMonth() As Boolean
'finds the current date
Dim CurrentDate As Date
CurrentDate = CDate(ActiveSheet.Cells(FIRST_DATA_ROW, 1))
'find filepath and filename of the monthly documentation file
Dim mFilePath As String
Dim mFileName As String
mFilePath = "F:\Project Sweep\Kim Checklist\Barry Polinsky\Brathwaite, Tamika\"
mFileName = Cells(3, 4) & ".m_d.xlsm"
'if it is the last week of the month, write a monthly report, and return true to continue with the face to face paperwork
If (31 - Day(CurrentDate)) <= 7 Then
'write a monthly report
Dim app As New Excel.Application
Dim book As Excel.Workbook
' app.Visible = False 'Visible is False by default, so this isn't necessary
Set book = app.Workbooks.Add(mFilePath & mFileName)
'run the subroutine CheckSpreadsheet in module WriteReport in target book
app.Run "'" & mFilePath & mFileName & "'!" & "WriteReport" & ".CheckSpreadsheet", book
' CheckSpreadsheet (book)
'error next line
book.Save
book.Close
app.Quit
Set app = Nothing
LastWeekOfMonth = True
'if it is not, simply continue with the face to face paperwork
Else
LastWeekOfMonth = False
End If
End Function
In the target worksheet, in module WriteReport, subroutine CheckSpreadsheet, the following code is located.
Option Explicit
Public Sub CheckSpreadsheet(wbook As Excel.Workbook)
Set wosheet = wbook.Sheets("Monthly")
wosheet.Cells(5, 5) = "Hello world!"
End Sub
Don't need to have another instance of Excel, the property to hide a workbook is Windows, in order to hide the excel windows used by the workbook. Also bear in mind that a workbook can have more than one window.
If you are sure that the workbook you want to hide has only one window use this line:
Workbooks("WbkName").Windows(1).Visible = False
If the workbook has several windows use this procedure:
Sub Wbk_Hide()
Dim wbk As Workbook, wdw As Window
Set wbk = Workbooks("WbkName") 'Update as required
For Each wdw In wbk.Windows
wdw.Visible = False
Next
End Sub
I believe this changes the scope of your procedures, let me know otherwise.
I'm having an issue in excel VBA with application.displayalerts = false.
When I send this command line in my program the displayalerts properties don't change to false, it remains true. When I execute it in the immediate window it turns to false. I couldn't find anything related to that.
I've already checked for the EnableEvent properties as I found on another topic, it is enabled.
I'm not sure which part of my code I should post because I tried this command both where I want it, in the middle of my code and as the first line of code. Also, this is running on an excel file which has other modules, some of them have public functions (which shouldnt affect anything) and some have public variables that I pasted below. Other than that, this is a complete independent code that don't really on the other ones
Public pctCompl As Integer
Public statCol As Collection
Public session As NotesSession
Public db As NotesDatabase
Public lmt As Integer
The code I'm using for the display alert
Application.DisplayAlerts = false
Let me know what else info you guys need or code
EDIT:
here's the code. Right after the line is executed the displayalerts propertie is still set to true, so it's not the case of it being set to true in other part of the code, the line is not changing the propertie, which is very strange because it does change it when I execute it on the immediate window
Sub Main()
Dim Mwksh As Worksheet
Dim Metwksh As Worksheet
Dim Swksh As Worksheet
Application.DisplayAlerts = False ''''''Dont work
'Set the worbooks
Set Mwksh = ThisWorkbook.Sheets(MASTER_SHT)
Set Swksh = ThisWorkbook.Sheets(SUPPORT_SHT)
'Open the Metrics workbook
Set Metwksh = OpenFile
'Find the Master File last column and row
clLast = LastCol(Mwksh, MASTER_HEADER_ROW)
rwLast = LastRow(Mwksh)
'Copy the content from the master file to the support sheet so it can be fixed before being copied to the metrics file
Swksh.UsedRange.ClearContents
Mwksh.Range(MASTER_FIRST_COL & MASTER_HEADER_ROW & ":" & clLast & rwLast).Offset(1, 0).Copy Destination:=Swksh.Range("A1")
DeleteColumns Swksh
InsertColumns Swksh
ClearDataSheet Metwksh
CopyToData Swksh, Metwksh
Metwksh.Parent.RefreshAll
Metwksh.Parent.Close savechanges:=True
MsgBox "Metrics file updated!"
End Sub
Use
Application.DisplayAlerts = False
Your code here
Application.DisplayAlerts = True
You forgot the s on end
If this does not solve the problem, use [your instance name].DisplayAlerts instead of Application.DisplayAlerts