简体   繁体   中英

Have macro in separate workbook to locate workbook, copy and paste as values from worksheet into new workbook and save in original workbook's location

As pre-warning, I am new to using VBA.

I have scraped together the following code to do the following: 1. Locate the worksheet "Intrastat" 2. Copy the used range of this worksheet 3. Paste as values into a new workbook 4. Reformat dates in column B 5. Save the workbook with in the original workbook's location.

However this only works when I have the macro saved in the original workbook. What I need is to be able to have the macro saved in a different workbook and on running the macro I need to be able to select the "original" workbook from a file location on my HDD.

Any ideas?

The Current Code:

Sub TB_Intrastat_Data_Cleanse()
Dim wb As Workbook
Set wb = Workbooks.Add
Set TWKB = ThisWorkbook
Set sel = Selection

Dim folderPath As String
folderPath = Application.ThisWorkbook.Path

TWKB.Sheets("Intrastat").UsedRange.Copy
wb.Sheets(1).[a1].PasteSpecial xlPasteValues
Columns("B:B").Select
Selection.NumberFormat = "dd/mm/yyyy;@"

nme = "TB Intrastat Data " & Range("A3") & " MTD"
ActiveWorkbook.SaveAs Filename:=folderPath & nme

End Sub

You can use Application.GetOpenFilename() to prompt the user to browse through the file explorer, and open a file. It will then use that file as TWKB :

Sub TB_Intrastat_Data_Cleanse()
Dim wb As Workbook, TWKB As Workbook
Dim sel As Range
Dim nme As String

Set wb = Workbooks.Add
Set TWKB = Application.GetOpenFilename(Title:="Please choose a file to open", FileFilter:="Excel Files *.xls* (*.xls*),")
Set sel = Selection

Dim folderPath As String
folderPath = Application.ThisWorkbook.Path

TWKB.Sheets("Intrastat").UsedRange.Copy
wb.Sheets(1).[a1].PasteSpecial xlPasteValues
Columns("B:B").NumberFormat = "dd/mm/yyyy;@"

nme = "TB Intrastat Data " & Range("A3") & " MTD"
ActiveWorkbook.SaveAs Filename:=folderPath & nme

End Sub

Note: I would change ActiveWorkbook.SaveAs at the end to a workbook variable (or explicitly name the workbook), since you're using two separate ones you want to make sure it's saving the correct one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM