I am generating 7 csv files and 1 excel file : A.xls from my R code. I need to copy each csv file to A.xls as a separate sheet and append it to A.xls
Can you just use VB to do the job, instead of VB?
' Merge data from multiple files into separate sheets
Sub R_AnalysisMerger2()
Dim WSA As Worksheet
Dim bookList As Workbook
Dim SelectedFiles As Variant
Dim NFile As Long
Dim FileName As String
Dim Ws As Worksheet, vDB As Variant, rngT As Range
Dim vFn, myFn As String
Application.ScreenUpdating = False
SelectedFiles = Application.GetOpenFilename(filefilter:="Excel Files (*.csv*), *.csv*", MultiSelect:=True)
If IsEmpty(SelectedFiles) Then Exit Sub
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
FileName = SelectedFiles(NFile)
vFn = Split(FileName, "\")
myFn = vFn(UBound(vFn))
myFn = Replace(myFn, ".csv", "")
Set bookList = Workbooks.Open(FileName, Format:=2)
Set WSA = bookList.Sheets(1)
vDB = WSA.UsedRange
bookList.Close (0)
Set Ws = Sheets.Add(after:=Sheets(Sheets.Count))
ActiveSheet.Name = myFn
Ws.Range("a1").Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
Next
Application.ScreenUpdating = True
End Sub
Related
I need to combine multiple workbook to one workbook.
Source workbooks have unique sheet name = "job"
Destination workbook have multiple sheets name
The Below code have 2 issues,
For loop not work
pasted data in Destination workbook create a new sheet. But i need to paste the data to existing sheet.
Sub combine()
'destination worksheets
Dim Ar As Worksheet
Dim nr As Worksheet
Set Ar = ThisWorkbook.Sheets("sheetAr")
Set nr = ThisWorkbook.Sheets("Sheetnr")
'Source workbooks
Dim FolderPath As String
Dim Filename As String
Application.ScreenUpdating = False
FolderPath = Environ("userprofile" & "\Desktop\Copy")
Filename = Dir(FolderPath & "*.xlsx*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
Dim ws As Worksheet
Dim AW As Workbook
Set AW = ActiveWorkbook
Set ws= ActiveWorkbook.Sheets("Job")
For Each AW In ws
AW.Activate
Cells.ShownAll
ws.Copy Ar
Next AW
Workbooks(Filename).Close savechanges = True
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
FolderPath = Environ("userprofile" & "\Desktop\Copy") should be FolderPath = Environ("userprofile") & "\Desktop\Copy\".For Each AW In ws makes no sense since AW is a workbook and ws a worksheet. You probably meant For Each ws in AW but there is no need to loop if only Job sheet is the source. Workbooks(Filename).Close savechanges = True is missing : but since the workbook was opened read-only there are no change to save so use .Close savechanges := False.
Option Explicit
Sub combine()
Dim wb As Workbook, rng As Range
Dim wsAr As Worksheet, wsSrc As Worksheet
Dim FolderPath As String, Filename As String
Dim iTargetRow As Long, c As Long, n As Long
FolderPath = Environ("userprofile") & "\Desktop\Copy\"
Filename = Dir(FolderPath & "*.xlsx*")
' destination worksheet
Set wsAr = ThisWorkbook.Sheets("sheetAr")
iTargetRow = wsAr.UsedRange.Row + wsAr.UsedRange.Rows.Count
Application.ScreenUpdating = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
Set wsSrc = wb.Sheets("Job")
Set rng = wsSrc.UsedRange
rng.Copy wsAr.Cells(iTargetRow, rng.Column)
iTargetRow = iTargetRow + rng.Rows.Count
wb.Close savechanges:=False ' opened read only
Filename = Dir()
n = n + 1
Loop
Application.ScreenUpdating = True
MsgBox n & " workbooks scanned", vbInformation
End Sub
When i use this code i get save as window and save workbook as i whish, but i also get one more workbook with active sheet from original, need help to get just one and if it is possible to close it after saving.
Code
Sub WorksheetSaveToNewWorkbook()
Dim loc As Variant
Dim Rng As Range
Dim newName As String
Dim newWkb As Workbook
Dim newWks As Worksheet
Dim Wks As Worksheet
Dim Shp As Shape
Application.DisplayAlerts = False
Set Wks = ThisWorkbook.ActiveSheet
Set Rng = Wks.Range("Q3:S170")
Data = Range("Q3:S170")
Wks.Copy
Set newWkb = Workbooks.Add
Set newWks = newWkb.ActiveSheet
With newWks
.Range("A1").Resize(UBound(Data, 1), UBound(Data, 2)).Value = Data
newName = " inklinometrija" & ".xlsx"
For Each Shp In .Shapes
Shp.OnAction = ""
Next Shp
loc = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Save As...", InitialFileName:=newName)
If loc <> False Then
ActiveWorkbook.SaveAs Filename:=loc, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
Exit Sub
End If
Application.DisplayAlerts = True
End With
End Sub
Wks.Copy
Set newWkb = Workbooks.Add
Set newWks = newWkb.ActiveSheet
Wks.copy is in fact the code to create a new workbook with just that worksheet.
I am trying to copy some data from one workbook to another, with checking certain cells content from 2 files. Below is my code:
Sub GetFileCopyData()
Dim Fname As String
Dim SrcWbk As Workbook
Dim DestWbk As Workbook
Dim miesiac() As Variant
Dim m_i, i, wiersz_nazw As Integer
Dim Msc, nazw As String
miesiac = Array(styczeń, luty, marzec, kwiecień, maj, czerwiec, lipiec, sierpień, wrzesień, październik, listopad, grudzień)
Set DestWbk = ThisWorkbook
Set SrcWbk = ActiveWorkbook
Fname = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a File")
If Fname = "False" Then Exit Sub
Set SrcWbk = Workbooks.Open(Fname)
Set DestWbk = ActiveWorkbook
Msc = SrcWbk.Cells(2, 13).Text
m_i = szukaj(miesiac, Msc)
nazw = Cells(3, 4).Text
For i = 1 To 100 Step 1
If nazw Like "*" & SrcWbk.Cells(i, 24) & "*" Then
wiersz_nazw = i: Exit For
End If
Next
SrcWbk.Cells(wiersz_nazw, 2).Copy DestWbk.Cells(m_i + 7, 3)
End Sub
Function szukaj(ByRef lista As Variant, ByVal wartosc As String)
Dim found As Integer, foundi As Integer ' put only once
found = -1
For foundi = LBound(lista) To UBound(lista):
'If lista(foundi) = wartosc Then
If StrComp(lista(foundi), wartosc, vbTextCompare) = 0 Then
found = foundi: Exit For
End If
Next
szukaj = found
End Function
It gets runtime 438 error in this line:
Msc = SrcWbk.Cells(2, 13).Text
The script have to get text parameter from source workbook cell 2,13, then take number for this text from array. Then scrip has to get text parameter from destination work book cell 3,4 and search for it in source workbook. Then I can copy some data.
This covers most of the comments. I think it should work, but you might have to check the workbook/sheet names as I wasn't entirely clear in all cases.
And check I have the wiersz_nazw bit correct.
The original 438 error was caused because Cells needs a sheet parent, not a workbook parent.
Sub GetFileCopyData()
Dim Fname As String
Dim SrcWbk As Workbook
Dim DestWbk As Workbook
Dim miesiac() As Variant
Dim m_i As Variant, i As Long, wiersz_nazw As Variant
Dim Msc As String, nazw As String 'each one needs to be specified
miesiac = Array(styczen, luty, marzec, kwiecien, maj, czerwiec, lipiec, sierpien, wrzesien, pazdziernik, listopad, grudzien)
Set DestWbk = ThisWorkbook 'file containing code
Fname = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a File")
If Fname = "False" Then Exit Sub
Set SrcWbk = Workbooks.Open(Fname)
Msc = SrcWbk.Worksheets(1).Cells(2, 13).Text
m_i = Application.Match(Msc, miesiac, 0)
If Not IsNumeric(m_i) Then m_i = -1
nazw = SrcWbk.Worksheets(1).Cells(3, 4).Text 'change workbook/sheet as necessary
wiersz_nazw = Application.Match("*" & nazw & "*", SrcWbk.Worksheets(1).Range("X1:X100"), 0)
If IsNumeric(wiersz_nazw) Then
SrcWbk.Worksheets(1).Cells(wiersz_nazw, 2).Copy DestWbk.Worksheets(1).Cells(m_i + 7, 3) 'change sheets as necessary
End If
End Sub
I have workbook, I loop through and save each sheet as a csv. The problem is when the loop finishes Excel prompts me to save. If I click "Save", then last worksheet is overwritten with whichever sheet the excel workbook opens on.
If click "Don't Save" everything remains saved with the proper data, but I can't rely on the user to click "Don't Save" every time so I need to find where my code is over writing the data when saved.
How do I keep my csv sheet from being overwritten?
Sub LipperFormat()
'Create Workbook
Dim wb As Workbook
'Get FilePath
Dim wbActive As Workbook
Set wbActive = ActiveWorkbook
Dim wsActive As Worksheet
Set wsActive = wbActive.Worksheets(1)
'Get File Path
Dim filePath As String
Dim rngActive As Range
Set rngActive = wsActive.Cells(1, 2)
filePath = rngActive.Value
'Open File
Set wb = Workbooks.Open(filePath)
'Create Copy of file and CSV
Dim copyFilePath As String
Dim fileExtension As String: fileExtension = "_OG.xlsx"
copyFilePath = Left(filePath, Len(filePath) - 5) + fileExtension
wb.SaveCopyAs copyFilePath
'Loop through worksheets
Dim WS_Count As Integer
Dim i As Integer
WS_Count = wb.Worksheets.Count
For i = 1 To WS_Count
Dim col As Integer
Dim ws As Worksheet
Set ws = wb.Sheets(i)
'Save As CSV
Dim sheetName As String: sheetName = ws.Name
Dim csvFilePath As String
Dim csvSheet As Worksheet
cvsFilePath = Left(filePath, Len(filePath) - 5) + "__" + sheetName
'ws.Name = sheetName
ws.SaveAs FileName:=cvsFilePath, FileFormat:=xlCSV, CreateBackup:=False
Next i
'wb.Save
wb.Close
End Sub
You code is too large for no benefits. I cleaned it and corrected your mistakes and also added necessary pieces to not ask the users for anything:
Sub LipperFormat()
Dim filePath As String
Dim csvFileName As String
Dim ws As Worksheet
Dim wb As Workbook
Application.DisplayAlerts = False
'define parameters
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1) 'it is better to define it with the name, not with its index
filePath = ws.Cells(1, 2).Value
'Open File
Set wb = Workbooks.Open(Filename:=filePath, ReadOnly:=True)
'loop and save as csv
For Each ws In wb.Worksheets
csvFileName = wb.Path & "\" & Left(wb.Name, Len(wb.Name) - 5) & "__" & ws.Name
ws.Copy
ActiveWorkbook.SaveAs Filename:=csvFileName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next ws
'close WB
wb.Close
Application.DisplayAlerts = True
End Sub
i am trying to replace the current data in my file with the data in any another selected file which have same attributes. i want to replace the data from A1:Q in the current file from any other selected file. I tried writing the code but its showing errors .
Sub newdata()
Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
'Open Source File.xlsx
With appxl
vFile = Application.GetOpenFilename(Title:="Select File To Be Opened")
If vFile = False Then Exit Sub 'if the user didn't select a file, exit sub
' Set myfile = Workbooks.Open(vFile)
.Visible = False
End With
'Get first sheet data
Set myfile = appxl.Windows(vFile)
myfile.Activate
Set currentSheet = myfile.Sheets(1)
'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
appxl.Workbooks(vFile).Close
End Sub
This is not the prettiest of codes but it works just as you asked!
Sub newdata()
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
Dim sourcefileworksheet As String
Dim destinationwb As String
Dim destinationwksheet As String
'set destination worksheet as open workbook when you run macro
destinationwb = ActiveWorkbook.Name
destinationwksheet = ActiveSheet.Name
'Select source file
Dim fNameAndPath As Variant, wb As Workbook
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
' cancel macro if nothing selected
If fNameAndPath = False Then
MsgBox ("Nothing Selected, Macro Cancelled")
Exit Sub
End If
'Open Source File.xlsx
Workbooks.Open (fNameAndPath)
'set source names
sourceFileName = ActiveWorkbook.Name
sourcefileworksheet = ActiveSheet.Name
'Determine last row of source
lastRow = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1").End(xlDown).Row
'Past the table in my current Excel file - Note that you should change the range of destination to A1:Q if you want all copied
Workbooks(destinationwb).Worksheets(destinationwksheet).Range("A1:E" & lastRow) = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
Workbooks(sourceFileName).Close
'Confirm complete
MsgBox ("Complete!")
End Sub