Copy data from a given filename/path vba - vba

I'm trying to create an excel tool where it would extract data from a given filename(workbook). Let's say, on my main workbook in(Sheet1-Cell A1), users will enter the filename. Then on a cmdbutton click, it'll copy the data from that specific filename(workbook).
I have created a file that copies data from another workbook, however, it indicates the specific path & filename of the workbook where the data will be copied.
Dim myData As Workbook
Set myData = Workbooks.Open("C:\Users\Desktop\Book2.xlsx")
Call Sample
Selection.Copy
What I want, is to allow users to just enter the filename, then excel will locate that file, select data from there & copy it on the main workbook(Sheet2).

I figured something out
Sub copydata()
Dim path As String
path = InputBox("Please input path")
Application.ScreenUpdating = False
Dim actualfile As Workbook
Set actualfile = ActiveWorkbook
Dim script As Object
Set script = CreateObject("Scripting.FileSystemObject")
Dim catalogue As Object
Set catalogue = script.GetFolder(path)
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Dim textfile As Object
For Each textfile In catalogue.Files
Workbooks.Open textfile
Dim loadedfile As Workbook
Set loadedfile = ActiveWorkbook
loadedfile.Worksheets(1).Range("A2").CurrentRegion.Offset(1, 0).Copy
actualfile.Worksheets(1).Range("A2").Offset(1, 0).End(xlUp).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
loadedfile.Close Savechanges:=False
Next textfile
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
The only problem though is, it copies data to the column after the heading instead of copying it to the row below the heading - help on this is very much appreciated! :)

Related

Copy a worksheet to a new workbook with paste values and keeping formats

I am trying to copy one worksheet to a new workbook, pasting all formulas as values while remaining all formats, sheetname, etcetera. The new file name should be "University" and stored on the same location as the original file.
I have been struggling with this, as it keeps returning an
"Error 1004: PasteSpecial method of Range class failed"
with my current (copied) script:
Sub new_workbook()
Dim Output As Workbook
Dim FileName As String
Set Output = Workbooks.Add
Application.DisplayAlerts = False
ThisWorkbook.Worksheets("Report").Copy
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
FileName = ThisWorkbook.Path & "\" & "University.xlsx"
Output.SaveAs FileName
End Sub
Worksheet.Copy with no Before or After specified creates a new workbook, so just work off of that.
More detail from the docs:
If you don't specify either Before or After, Microsoft Excel creates a new workbook that contains the copied Worksheet object. The newly created workbook holds the Application.ActiveWorkbook property and contains a single worksheet.
Sub new_workbook()
ThisWorkbook.Worksheets("Report").Copy '<-- creates a new workbook with a copy of your sheet
Dim Output as Workbook
Set Output = ActiveWorkbook
With Output.Worksheets(1).UsedRange
.Value = .Value '<-- changes all formulas to values
End With
Dim FileName As String
FileName = ThisWorkbook.Path & "\University.xlsx"
Application.DisplayAlerts = False
Output.SaveAs FileName
End Sub

Run-time Error 9 w/Variable Workbook Name

So the user is able to import data from another excel file and I want to close the other excel file once the values have been copied into the current workbook. I can't, however, get my code to go back and select the other excel file in order to close it again.
I've already checked and it's only running one instance of Excel.
Option Explicit
Private Sub Button_ImportSubmittedData_Click()
Dim MyFile As String
Dim tempDataSetName As String
tempDataSetName = "Submitted Apps"
MyFile = Application.GetOpenFilename("Excel Files,*.xlsx")
Workbooks.OpenText Filename:=MyFile
ActiveSheet.Range("A2").Select
ActiveSheet.Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Windows("HET.xlsm").Activate
Sheets("Submitted").Select
ActiveSheet.Range("A2").Select
ActiveSheet.Paste
Selection.Columns.AutoFit
ActiveSheet.Range("A1").Select
**Windows(MyFile).Activate**
'Application.DisplayAlerts = False
'ActiveWindow.Close
'Windows("HET.xlsm").Activate
'ActiveSheet.Range("A1").Select
End Sub

Excel VB works fine on SharePoint. Move to my C;Drive change the path and it does not

You helped me create this set of code. The workbooks are on a sharepoint and they work fine.
Private Sub CommandButton1_Click()
Dim DestWb As Workbook 'define destination workbook
Set DestWb = Workbooks.Open(Filename:="C:\Users\Paul Webb\Cats Protection\Crawley Branch Site - Finance Documents\Adoptions\Testing Area\summary sheet - testing .xls")
Dim DestWs As Worksheet 'define destination worksheet
Set DestWs = DestWb.Worksheets("Datainput")
Dim eRow As Long 'determine last row in destination worksheet
eRow = DestWs.Cells(DestWs.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'If eRow >= 1 Then eRow = eRow + 1
ThisWorkbook.Worksheets("Datasheet").Range("B1:B48").Copy 'copy directly before paste
DestWs.Cells(eRow, 1).PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=False, Transpose:=True
Application.CutCopyMode = False
DestWb.Close Save = True 'close and save destination workbook
End Sub
I have moved the files to my c drive and change the path in the code. But when I run the code I can see that it opens the target workbook but does not paste any of the data in to the spreadsheet. What have I missed please?
Private Sub CommandButton1_Click()
Dim DestWb As Workbook 'define destination workbook
Set DestWb = Workbooks.Open(Filename:="C:\Cats Protection\Adoption\summary sheet - testing.xlsx")
Dim DestWs As Worksheet 'define destination worksheet
Set DestWs = DestWb.Worksheets("Datainput")
Dim eRow As Long 'determine last row in destination worksheet
eRow = DestWs.Cells(DestWs.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'If eRow >= 1 Then eRow = eRow + 1
ThisWorkbook.Worksheets("Datasheet").Range("B1:B48").Copy 'copy directly before paste
DestWs.Cells(eRow, 1).PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=False, Transpose:=True
Application.CutCopyMode = False
DestWb.Close Save = True 'close and save destination workbook
End Sub
Both codes have the issue that DestWb.Close Save = True is actually not doing what you assume, because you used it the wrong way.
I highly recommend to use Option Explicit (as first line in every VBA module/worksheet). This would have warned you because in your code Save is a not declared variable (instead of a parameter name).
Some background how to submit parameters to the .Close method
According to the documentation the Workbook.Close Method accepts the following parameters:
.Close(SaveChanges, Filename, RouteWorkbook)
So you have 2 possibilities to submit the parameters:
By parameter order (without parameter name), order as in documentation
.Close True, "C:\Temp\file.xlsx"
.Close "C:\Temp\file.xlsx", True '!! wrong parameter order !!
By parameter name (order of parameters is not relevant now)
.Close Filename:="C:\Temp\file.xlsx", SaveChanges:=True
.Close SaveChanges:=True, Filename:="C:\Temp\file.xlsx"
Both lines are equal.
Please not that parameters for a method must be set with a := instead of like variables are set with a = only. Also the parameter name is SaveChanges not Save.
What was the issue with your code?
In DestWb.Close Save = True your Save is a variable. Because it was not declared nor initialized it is Nothing. So Save = True actually evaluates to False and parameters are submitted by order, so it is actually the same like DestWb.Close False which means: "Close and don't save the workbook".

How do I remove the prompt to save information on clipboard?

I have a VBA script that allows me to select a file and then copies a range from that file and pasted it into the target worksheet. However every time I do this is opens the source file and then closes which prompts me if I want to save the information on the clip board.
I don't know if it would be better to just copy the data without opening the source excel.
Option Explicit
Sub DCDatabaseCopy()
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Dim DCRowCount As Integer
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
'-------------------------------------------------------------
'Open file with data to be copied
vFile = Application.GetOpenFilename("Excel Files (*.*)," & "*.*", 1, "Select Excel File", "Open", False)
'If Cancel then Exit
If TypeName(vFile) = "Boolean" Then
Exit Sub
Else
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
End If
'--------------------------------------------------------------
'Copy Range
DCRowCount = wsCopyFrom.Range("A1", wsCopyFrom.Range("A1").End(xlDown)).Rows.Count
wsCopyFrom.Range("A1:G" & DCRowCount).Copy
wsCopyTo.Range("A2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
End Sub
Before you close the workbook run:
wbCopyFrom.Application.CutCopyMode = False
This will clear the clipboard.
use these 2 lines of code before and after, it will bypass the clipboard prompt
Application.DiplayAlerts = FALSE
Application.DiplayAlerts = TRUE
Or it could be that you need to use this:
ActiveWindow.Close savechanges:=FALSE
Obviously if the file is not in the ActiveWindow then replace that part of the code with wherver it is

Use VBA to Grab Only Part of a Filename/Filepath

I'm not sure how to tackle this issue. I've done quite a bit of research, but most of the answers I find are a little different than what I need.
What I'm trying to accomplish is this:
Open up an existing workbook manually (wbAI),
Start macro,
Use msoFileDialogOpen to find and open a file (call this wb2),
Store part of wb2's file name (there is a date in the file name) as a variable or string. (I'm not sure which is better for this purpose. Maybe I don't need to store it all...),
Paste part of wb2's filename (the date) in a certain cell in wb1,
Copy the necessary data from wb2,
Paste the data in wb1,
Format the data,
Use a VLOOKUP on the pasted data,
Close wb2 without saving
End the macro.
My macro can do every step listed above except for numbers four and five. On one hand, I'm wondering how I need to pursue this, and on the other hand, I'm wondering where this would fit inside my current code.
To give you an example of what I'm talking about: let's say that in step three I open up a workbook that's named "01.31.13 Group Names." And the file path is from a Sharepoint site so it looks like this:
"https://company.com/team/teamone/_layouts/xlviewer.aspx?01.31.13%20Group%20Names%20.xlsm&Source=https......."
How can I pick out only the date in the filename/filepath?
Here's the beginning of my code:
Sub Test()
Dim lastRow As Long, i As Long
Dim ws As Worksheet
Dim wbSource As Workbook
Dim wbAI As Workbook
Dim vrtSelectedItem As Variant
Set wbAI = ActiveWorkbook
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = https://company.com/team/teamone & "\"
.AllowMultiSelect = False
.Show
' ****** Is this where the new code could be inserted? *******
For Each vrtSelectedItem In .SelectedItems
Set wbSource = Workbooks.Open(vrtSelectedItem)
Next
End With
' Check if the first cell contains data. If not then close file
If Range("Profile!H9") = "" Then
ActiveWorkbook.Close savechanges:=False
ActiveWorkbook.Saved = False
Any suggestions are welcome! Thank you for your time!
Edit: This is how my code looks after Philip's suggestion:
Sub Test()
Dim lastRow As Long, i As Long
Dim ws As Worksheet
Dim wbSource As Workbook
Dim wbAI As Workbook
Dim vrtSelectedItem As Variant
Set wbAI = ActiveWorkbook
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = https://company.com/team/teamone & "\"
.AllowMultiSelect = False
.Show
For Each vrtSelectedItem In .SelectedItems
Set wbSource = Workbooks.Open(vrtSelectedItem)
Next
End With
dateVar = Left(wbSource.Name, 8) '<~~~~ New code
' Check if the first cell contains data. If not then close file
If Range("Profile!H9") = "" Then
ActiveWorkbook.Close savechanges:=False
ActiveWorkbook.Saved = False
Else
Sheets("Profile").Activate
Range("H9:I" & Cells(Rows.Count, "H").End(xlUp).Row).Select
Selection.Copy
Windows("wbName").Activate
Sheets("Sheet1").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("E1").Value = dateVar '<~~~ New code
from the filename you would use the LEFT FUNCTION to return the LEFT 8 chars of the date:
dateVar=left(wbSource.name, 8)
then you can put that in your cell:
rangeVar.value=dateVar
hope that gets you going
Philip