Hi there,
I have been lately working with VBA and I got stuck, selecting the data I am interested in and copy it into a new workbook. I have seen examples and youtube videos but I have clearly missed something.
I have posted part of the code, as the rest is working fine:
Private Sub Obtain_Data_Click()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim SelectedFiles() As Variant
Dim NRow As Long
Dim FileName As String
Dim NFile As Long
Dim ThisWorkbook As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim i As Integer
Dim lastrow As Long, lastcolumn As Long
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\Mark\Desktop\PV Data"
' Set the current directory to the the folder path.
ChDrive FolderPath
ChDir FolderPath
' Open the file dialog box and filter on Excel files, allowing multiple files
' to be selected.
SelectedFiles = Application.GetOpenFilename( _
filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Loop through the list of returned file names
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
' Set FileName to be the current workbook file name to open.
FileName = SelectedFiles(NFile)
' Open the current workbook.
Set ThisWorkbook = Workbooks.Open(FileName)
'Copy column A
Dim sh1 As Worksheet, sh2 As Worksheet, p As Long
Dim j As Long, N As Long, r1 As Range
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = SummarySheet
N = sh1.Cells(Rows.Count, "A").End(xlUp).Row
j = p
For p = 1 To N
Set r1 = sh1.Cells(p, "A")
If r1.Value <> "" Then
r1.Copy sh2.Cells(j, "A")
j = j + p
End If
Next p
'Copy column A
Dim sh1 As Worksheet, sh2 As Worksheet, p As Long
Dim j As Long, N As Long, r1 As Range
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = SummarySheet
N = sh1.Cells(Rows.Count, "A").End(xlUp).Row
j = p
For p = 1 To N
Set r1 = sh1.Cells(p, "A")
If r1.Value <> "" Then
r1.Copy sh2.Cells(j, "A")
j = j + p
End If
Next p
' Set the cell in column F2 to be the file name.
SummarySheet.Range("A2").Value = ActiveWorkbook.Name
SummarySheet.Range("A1").Value = "Name of the Site"
Basically I want to copy several (but not all) columns from the opened file, into specific columns inside the new workbook.
Any help is highly appreciated
Many Thanks
Ricardo
Bookmarks