I've a scenario in which i'm copying data from multiple files to master files, I want when the program run at first time it should start pasting the data at my specified range in the master file which is working fine. But when the program is run again it's not going to start from the previous range rather it's start pasting data below at the previous record which is duplication of the same data, I want that when user first time or as many time run the program program range start at the same location where it was at first time running.
Following is my code.
Sub Append()
'Append data from other files
Path = "E:\NPM PahseIII\"
Dim c As Range
'find the second empty cell in ColA
Set c = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
'target range for pasting data it first run this is actually pointing to
'my desire range but at second or multiple running the range is starting
'below at the previous record
Set targetcellL = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 1)
Set targetcellR = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(5, 4)
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
If InStr(Filename, ".") > 0 Then
Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If
c.Value = Filenamenoext
Set c = c.Offset(4, 0)
Set wb = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
Data = wb.Worksheets(1).Range("B3:E6").Value
wb.Worksheets(1).Range("B3:E6").Copy
ThisWorkbook.Activate
ActiveSheet.Range(targetcellL, targetcellR).Select
ActiveSheet.Paste
Set targetcellL = targetcellL.Offset(4, 0)
Set targetcellR = targetcellR.Offset(5, 0)
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Problem: I want that when the program as run as many time it should start pasting Data it the Range where it is pasting data for the first time.
Following images will clear my problem more precisely.
When the program run for the first time i get pasted data it below range which is what i want.
When Run for the 2nd time i get data it below range
what should i do to make the behavior as such that when the program run for as many time the data should paste at the range where it's at first run see pic.
Here are two different ways to do it:
Sub AppendValuesAndFormats()
'Append data from other files
Const Path = "E:\NPM PahseIII\"
Dim target As Range
With ThisWorkbook.ActiveSheet
.UsedRange.Offset(2).ClearContents
Set target = .Range("A3")
End With
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
With Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
target.Value = IIf(InStr(Filename, ".") > 0, Left(Filename, InStr(Filename, ".") - 1), "")
.Worksheets(1).Range("B3:E6").Copy Destination:=target.Offset(0, 1)
.Close SaveChanges:=False
End With
Set target = target.Offset(4)
Filename = Dir()
Loop
End Sub
Sub AppendValues()
'Append data from other files
Const Path = "E:\NPM PahseIII\"
Dim target As Range
With ThisWorkbook.ActiveSheet
.UsedRange.Offset(2).ClearContents
Set target = .Range("A3")
End With
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
With Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
target.Value = IIf(InStr(Filename, ".") > 0, Left(Filename, InStr(Filename, ".") - 1), "")
target.Range("B1:E4").Value = .Worksheets(1).Range("B3:E6").Value
.Close SaveChanges:=False
End With
Set target = target.Offset(4)
Filename = Dir()
Loop
End Sub
Related
So, I renamed and moved some workbooks that are linked together and I need to update their xlExcelLinks on VBA, the thing is, I have a list of the references to update, but I can't figure out how to update only the ones I need and not every reference on the book.
The initial idea was to search for matching strings between a file name and the stored reference's path. Example data:
A2 Cell on Data.xlsx
Change to
I have this guide example code:
Sub Relink()
Dim previousFile, newFile, oldPath, newPath, Macro, altTab As String
'Macro stores the name of the file running the macro and altTab the name of the file to update
Dim ref as xlExcelLink 'Clearly not a type of data but I need something similar
Windows(Macro).activate
For I = 2 To 4
oldPath = Range("L"& I).Value
newPath = Range("M" & I).Value
previousFile = Range("N" & I).Value
newFile = Range("O" & I).Value
Windows(alTab).activate
'Somehow check for every reference avoiding itself
If ref.Address = oldPath & "\" & previousFile Then
ActiveWorkbook.ChangeLink Name:=oldPath & "\" & previousFile, _
NewName:=newPath & "\" & newFile, Type:=xlExcelLinks
End If
Next
End Sub
Note that on some files there could be only 1 update needed from 50ish references.
Try this code:
Sub UpdateLinks()
'Reference to your change list.
'ThisWorkbook is the file containing this code.
Dim ChangeList As Range
Set ChangeList = ThisWorkbook.Worksheets("Sheet2").Range("A2:D4")
'The workbook containing the links to change.
Dim wrkBk As Workbook
Set wrkBk = Workbooks("Test Timesheet.xlsx")
'If workbook isn't open use:
'Set wrkbk = workbooks.Open(<path to workbook>)
'Look at each link in the workbook.
'lnk must be Variant so it can be used in the For Each loop.
Dim lnk As Variant
For Each lnk In wrkBk.LinkSources
Dim OldPath As String
OldPath = Left(lnk, InStrRev(lnk, "\") - 1)
Dim OldFileName As String
OldFileName = Mid(lnk, InStrRev(lnk, "\") + 1, Len(lnk))
'Search for the existing path in first column of ChangeList.
Dim FoundLink As Range
Set FoundLink = ChangeList.Columns(1).Find(OldPath, , xlValues, xlWhole, xlByRows, xlNext)
'If it's not found, then continue to the next link.
'If it is found check that OldName also exists on that line, if it doesn't then continue searching.
If Not FoundLink Is Nothing Then
Dim firstAdd As String
firstAdd = FoundLink.Address
Do
If FoundLink.Offset(, 2) = OldFileName Then
'Found the link we're after so exit the loop.
Dim NewPath As String
NewPath = FoundLink.Offset(, 1)
Dim NewFileName As String
NewFileName = FoundLink.Offset(, 3)
Exit Do
Else
'Continue searching.
Set FoundLink = ChangeList.Columns(1).FindNext(FoundLink)
End If
Loop While firstAdd <> FoundLink.Address
'Make the change.
wrkBk.ChangeLink Name:=OldPath & Application.PathSeparator & OldFileName, _
NewName:=NewPath & Application.PathSeparator & NewFileName
End If
Next lnk
End Sub
I have a Code, that copies Data from other files and put them in to a table (opened Workbook). How can i exclude opened Workbook (from where i starting the macro) and for example some specific files (C:\Users\Desktop\text.xlsm) from the loop? I tried with If strFile <> ActiveWorkbook.Name Then but it doesn't work, it still try to open the opened Workbook.
Here a part of the Code with the Loop:
Set oWks0 = ActiveSheet
aCells = Split(Zellen, ",")
iNextLine = iStartZeile
For ialngFolders = LBound(avntFolders) To UBound(avntFolders)
strFile = Dir$(avntFolders(ialngFolders) & "*.xlsm")
Do Until strFile = vbNullString
Set oWkb1 = Workbooks.Open(avntFolders(ialngFolders) & strFile)
Set oWks1 = oWkb1.Sheets(1)
For i = 0 To UBound(aCells)
'If strFile <> ActiveWorkbook.Name Then
oWks0.Cells(iNextLine, iStartSpalte).Offset(0, i).Value = _
oWks1.Range(aCells(i)).Value
'End If
Next
Call oWkb1.Close(SaveChanges:=False)
iNextLine = iNextLine + 1
strFile = Dir$
Loop
Next
Workbooks.Open is the method to open workbook
Using
If strFile <> ActiveWorkbook.Name Then
before the line
Set oWkb1 = Workbooks.Open(avntFolders(ialngFolders) & strFile)
Below is my code
Sub Append()
'Append data from other files
Path = "E:\NPM PahseIII\"
Filename = Dir(Path & "*.xlsx")
If InStr(Filename, ".") > 0 Then
Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If
MsgBox Filenamenoext
Range("A3").Select
Do While Filename <> ""
ActiveCell.Value = Filenamenoext
Loop
End Sub
My problem is that as I've selected Range("A3").Select is hard coded, i want this selection to be done dynamically in loop such that when the first iteration of the loop start it should select Range("A3").Select & further select next cell in the next iteration.
How can i achieve this?
Edited
See image below
Like this (untested):
Sub Append()
Const FPath As String = "E:\NPM PahseIII\"
Dim c As Range, Filename
'find the first empty cell in ColA
Set c = activesheet.cells(rows.count, 1).end(xlup).offset(1, 0)
Filename = Dir(FPath & "*.xlsx")
Do While Filename <> ""
c.Value = Split(Filename, ".")(0) 'note: problem if any of your file names have embedded periods...
Set c = c.offset(1, 0)
Filename = Dir()
Loop
End Sub
I have some folders with hundreds of reports - all reports are the same, and there´s nothing else in that folders.
I should take multiple workbooks like the first one in the image, and recopilate them in a master file (second image).
I have some code - below - but I don´t know how to complete it; The workbook is a template, so it always have 15 rows (could be completed or not) and I need to bring all that´s there plus the date and group control, which is shared by every document inside the file.
I´d appreciate if you could help me complete the code; somebody told me this could be done using powerquery but I´ve never used it. If you think this would be easier, please let me know your thoughts.
Thanks!!
What I have:
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Path = "C:\Users\Maudibe\Desktop\ExcelFiles\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
'
' **WHAT TO DO HERE?**
'
MsgBox Filename & " has opened"
wbk.Close True
Filename = Dir
Loop
End Sub
So i modified your code to this: (Has to be in ThisWorkbook)
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim sht, msht As Worksheet
Dim lRowFile, lRowMaster As Long
Dim FirstDataSet As Integer
Path = "C:\Users\User\Desktop\Files\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Filename <> "" And Filename <> "Master.xlsm" 'Dont Open MasterFile 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
Set sht = Workbooks(Filename).Worksheets(1) 'First Sheet in File
Set msht = ThisWorkbook.Worksheets(1) 'First Sheet in Master
lRF = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Last Row in File
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
FirstDataSet = 5 'First Data Set in File
For i = FirstDataSet To lRF
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
msht.Range("A" & lRM + 1).Value = sht.Range("A" & i).Value 'DocumentName
msht.Range("B" & lRM + 1).Value = sht.Range("B" & i).Value 'Amount
msht.Range("C" & lRM + 1).Value = sht.Range("D2").Value 'Date
msht.Range("D" & lRM + 1).Value = sht.Range("D3").Value 'Group #
Next i
wbk.Close True
Filename = Dir
Loop
End Sub
It will open the workbooks and check which rows are filled in Col A (Non used have to be blank). Then it copies the Data to the Master File. My Workbooks that have been opened looked like this and the Result:
I am attempting to use VBA to open all the excel files in a directory (in this case c:\temp) and put all the files datasheets in one large file. Each new sheet is named with the filename plus the name of the sheet on the original document. The code that I have copies the first file's first sheet and even names it correctly, but then fails with a Run-time error 1004: Application defined or object defined error on the second sheet when I try to set the name. Anyone have any suggestions on how to fix.
Sub MergeAllWorkbooks()
Dim FolderPath As String
Dim FileName As String
' Create a new workbook
Set FileWorkbook = Workbooks.Add(xlWBATWorksheet)
' folder path to the files you want to use.
FolderPath = "C:\Temp\"
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
Windows(WorkBk.Name).Activate
For Each currentSheet In WorkBk.Worksheets
currentSheet.Select
currentSheet.Copy Before:=Workbooks(FileWorkbook.Name).Sheets(sheetIndex)
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
sheetIndex = sheetIndex + 1
Next currentSheet
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
End Sub
Replace
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
with (I separated it out for readability)
sWSName = FileName & "-" & currentSheet.Name
sWSName = NameTest(sWSName)
sWSName = TestDup(sWSName)
FileWorkbook.Sheets(sheetIndex).Name = sWSName
You will need to define the sWSName.
Below are the modified functions I have previously used.
Function NameTest(sName As String) As String
NameTest = sName
aSpecChars = Array("\", "/", "*", "[", "]", ":", "?")
For Each c In aSpecChars
NameTest = Replace(NameTest, c, "")
Next c
If Len(sName) > 31 Then NameTest = Left(sName, 31)
End Function
Function TestDup(sWSName As String) As String
TestDup = sWSName
For Each ws In Worksheets
Debug.Print ws.Name
If sWSName = ws.Name Then TestDup = TestDup(Left(sWSName, Len(sWSName) - 1))
Next ws
End Function
If posting this code (or to this extent) is out of line please let me know as I am still coming to terms with the level of effort require versus reasonable response.