Hi I have this macro and a few others that are similar that struggle when the worksheet names include "-", " ", "(" or ")". It normally fails on line when the graph series is created ActiveChart.FullSeriesCollection(1).XValues = "=" & ws.Name & "!$G$61:$G$" & iBas In the debugger when I hover over ws.Name it says Automation Error.
I have got around this by changing the worksheet names to remove these characters but I would like to understand why it fails and what if anything I can do to leave the worksheet names as they are?
Sub COREStepChart()
'
' Insert additional rows to have x value for base of core run in order to create bar/step shaped chart by depth/elevation and update graph series to new array
' Macro created by Dan Brenton 20200814
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim wb As Workbook
Dim ws As Worksheet
Dim strRef, strRange As String
Dim iRow, iBase, iTCR, iSCR, iRQD, iDepthBase, iOrder As Integer
Set wb = ThisWorkbook
For Each ws In wb.Worksheets
Select Case ws.Name
Case "Template", "Report", "Configuration (CORE)", "Configuration (Moisture)"
Case Else
ws.Name = Replace(ws.Name, "-", "")
ws.Name = Replace(ws.Name, " ", "")
ws.Name = Replace(ws.Name, "(", "")
ws.Name = Replace(ws.Name, ")", "")
ws.Activate
iTop = 61
iBase = 62
iLoca = 2
iDepthTop = 5
iDepthBase = 6
iTCR = 7
iSCR = 8
iRQD = 9
iOrder = 12
iElev = 17
Do While ws.Cells(iTop, iTCR) <> ""
Rows(iBase & ":" & iBase).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range(Cells(iTop, iLoca), Cells(iTop, iElev)).Select
Selection.Copy
Cells(iBase, iLoca).Select
ActiveSheet.Paste
Cells(iTop, iDepthBase).Select
Selection.Copy
Cells(iBase, iDepthTop).Select
ActiveSheet.Paste
Cells(iTop, iOrder).Select
ActiveCell.FormulaR1C1 = "1"
Cells(iBase, iOrder).Select
ActiveCell.FormulaR1C1 = "2"
iTop = iTop + 2
iBase = iBase + 2
Loop
ActiveSheet.ChartObjects("Chart2").Activate
ActiveChart.PlotArea.Select
ActiveChart.FullSeriesCollection(1).XValues = "=" & ws.Name & "!$G$61:$G$" & iBase
ActiveChart.FullSeriesCollection(1).Values = "=" & ws.Name & "!$Q$61:$Q$" & iBase
ActiveChart.FullSeriesCollection(2).XValues = "=" & ws.Name & "!$H$61:$H$" & iBase
ActiveChart.FullSeriesCollection(2).Values = "=" & ws.Name & "!$Q$61:$Q$" & iBase
ActiveChart.FullSeriesCollection(3).XValues = "=" & ws.Name & "!$I$61:$I$" & iBase
ActiveChart.FullSeriesCollection(3).Values = "=" & ws.Name & "!$Q$61:$Q$" & iBase
ActiveSheet.ChartObjects("Chart5").Activate
ActiveChart.PlotArea.Select
ActiveChart.FullSeriesCollection(1).XValues = "=" & ws.Name & "!$G$61:$G$" & iBase
ActiveChart.FullSeriesCollection(1).Values = "=" & ws.Name & "!$E$61:$E$" & iBase
ActiveChart.FullSeriesCollection(2).XValues = "=" & ws.Name & "!$H$61:$H$" & iBase
ActiveChart.FullSeriesCollection(2).Values = "=" & ws.Name & "!$E$61:$E$" & iBase
ActiveChart.FullSeriesCollection(3).XValues = "=" & ws.Name & "!$I$61:$I$" & iBase
ActiveChart.FullSeriesCollection(3).Values = "=" & ws.Name & "!$E$61:$E$" & iBase
End Select
Next
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Related
I cannot seem to get this line of code working:
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=INDEX('" & cNameAndPath & BET_ws.Cells(errCell.Row,
2).Value & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cNameAndPath &
BET_ws.Cells(errCell.Row, 2).Value & "'!R2C2:R400C2,0),MATCH(RC3,'" & cNameAndPath
& BET_ws.Cells(errCell.Row, 2).Value & "'!R1C3:R1C200,0))"
Next errCell
I keep getting an object undefined error. Is it a problem with my R1C1 notation or is it an issue with BET_ws.Cells(errCell.Row,2).Value statement? In Column B the tab name needed for my INDEX reference is in the RC2 location. Not sure how to correct the issue. cNameAndPath is defined and is pulling the value I want. Another formula is running in the adjacent range with no problem.
Here is most of the code if it helps:
Sub BetConverter()
Dim wbkTarget As Workbook
Dim fNameAndPath As Variant
Dim cNameAndPath As Variant
Dim cFileName As String
Dim cFilePath As String
Dim BET_ws As Worksheet
Dim shtTarget As Worksheet
Dim ws As Worksheet
Dim lrow As Long 'last row variable
Dim lcol As Long 'last column variable
Dim lastrow As Long
Dim i As Integer
Dim cwbTarget As Workbook
Dim errCell As Range
'kill clunky processes
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
'delete summary tab if it exists
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Sheets("BET Consolidated").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'On Error GoTo Errhandler
Sheets.Add(After:=Sheets("Macro")).Name = "BET Consolidated" 'create new tab
Set BET_ws = ThisWorkbook.Sheets("BET Consolidated")
MsgBox ("Please Select the Bid Entry Tool to be Consolidated in the following File Dialog Box.")
fNameAndPath = Application.GetOpenFilename(Title:="Select Bid Entry Tool to be Consolidated")
If fNameAndPath = False Then Exit Sub
Set wbkTarget = Workbooks.Open(fNameAndPath)
MsgBox ("Please Select the MDB for Comparison in the following File Dialog Box.")
cNameAndPath = Application.GetOpenFilename(Title:="Select the MDB for Comparison")
If cNameAndPath = False Then Exit Sub
Set cwbTarget = Workbooks.Open(cNameAndPath)
cFileName = Mid$(cNameAndPath, InStrRev(cNameAndPath, "\") + 1)
cFilePath = Left$(cNameAndPath, InStrRev(cNameAndPath, "\"))
Do While shtTarget Is Nothing
For Each ws In wbkTarget.Sheets
If ws.Name Like "*H*" Then
Set shtTarget = ws
End If
Next ws
Loop
lrow = shtTarget.Cells(Rows.Count, 11).End(xlUp).Row
With shtTarget.Range("K2:K" & lrow)
BET_ws.Range("A1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("J2:J" & lrow)
BET_ws.Range("B1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("O2:O" & lrow)
BET_ws.Range("C1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("P2:P" & lrow)
BET_ws.Range("D1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
i = 0
For Each ws In wbkTarget.Worksheets
If ws.Name Like "*H*" Then
Set shtTarget = ws
lastrow = shtTarget.Cells(shtTarget.Rows.Count, 27).End(xlUp).Row
With shtTarget.Range("AA1:AA" & lastrow)
BET_ws.Range(Range("D1").Offset(0, 1 + i).Address).Resize(.Rows.Count, .Columns.Count) = .Value
End With
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=INDEX('" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R2C2:R400C2,0),MATCH(RC3,'" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R1C3:R1C200,0))"
Next errCell
For Each errCell In BET_ws.Range("F5:F" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=IF(RC[-2]=RC[-1],""MATCH"",""DOES NOT MATCH"")"
Next errCell
i = i + 3
End If
Next ws
Also tried like this:
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
tName = BET_ws.Cells(errCell.Row, 2).Value
errCell.FormulaR1C1 = "=INDEX('" & cFilePath & "[" & cFileName & "]" & tName & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cFilePath & "[" & cFileName & "]" & tName & "'!R2C2:R400C2,0),MATCH(RC3,'" & cFilePath & "[" & cFileName & "]" & tName & "'!R1C3:R1C200,0))"
Next errCell
I have code below for a print function created in VBA. When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave". I cant see where I went wrong in my code or what is causing the issue... Any thoughts? Thanks in advance!
Sub pcf_print()
Dim ws As Worksheet
Dim datasheet As Worksheet
Dim fs As Object
Dim str As String
Dim bool As Boolean
If Len(ActiveSheet.Name) < 3 Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
If Left(ActiveSheet.Name, 3) <> "PCF" Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
'MsgBox Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v")) 'Right(ActiveSheet.Name, 4)
If InStr(ActiveSheet.Name, " vv") Then
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
Else
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) < 1.2 And (ActiveSheet.Range("F9") = "(select)" Or ActiveSheet.Range("F9") = "")) Or (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
End If
Set datasheet = ActiveSheet
If ActiveWorkbook.Worksheets("Form Lists").Range("CorpOrStore") = "Corp" Then
str = "Corporate"
Else
str = "Stores"
End If
Set fs = CreateObject("Scripting.FileSystemObject")
bool = fs.FolderExists("H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\")
If Not bool Then
MkDir "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\"
End If
If InStr(ActiveSheet.Name, " vv") Then
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
End If
Else
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
Else
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & datasheet.Range("F9") & " for " & datasheet.Range("J16") & ", " & datasheet.Range("F16") & " effective " & Month(datasheet.Range("F11")) & "-" & Day(datasheet.Range("F11")) & "-" & Year(datasheet.Range("F11")) & ".xls"
End If
End If
Set ws = ActiveWorkbook.Worksheets("Payroll Forms")
If Right(ActiveSheet.Name, 5) = "v1.20" Then
ActiveWorkbook.Worksheets("Form Lists").Unprotect "0nl1n3"
ActiveWorkbook.Worksheets("Form Lists").Range("B8") = "A1:G76"
ActiveWorkbook.Worksheets("Form Lists").Range("B9") = "A80:G157"
ActiveWorkbook.Worksheets("Form Lists").Range("B10") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B11") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B12") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B13") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B14") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B15") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B16") = "A343:G367"
ActiveWorkbook.Worksheets("Form Lists").Range("B17") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B18") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B19") = "A370:G420"
ActiveWorkbook.Worksheets("Form Lists").Protect "0nl1n3"
End If
If Right(ActiveSheet.Name, 5) = "v1.20" Or Right(ActiveSheet.Name, 5) = "v1.21" Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
ActiveWorkbook.Unprotect "0nl1n3"
ws.Visible = xlSheetVisible
ws.PrintOut
ws.Visible = xlSheetHidden
ActiveWorkbook.Protect "0nl1n3"
ActiveWorkbook.Close False
End Sub
OP says:
When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave"
Assuming that the
"salary" change type
corresponds to the "default print" i.e.:
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
It seems that the reason the code provided always prints the default range, it's because the lines that determine the printed output are validating the ActiveSheet.Name instead of the value in the "Type of Change field and print"
Solution proposed:
Change these lines to reflect the cell where the "Type of Change field and print" is located:
Replace ActiveSheet.Name with the corresponding cell.address i.e.: F10 and update as required the comparisons against "v1.20" and "v1.21"
If Right(ActiveSheet.Name, 5) = "v1.20" _
Or Right(ActiveSheet.Name, 5) = "v1.21" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
It should become (comparison values shown as a reference, they should be updated in line with the choices in the drop-down list) :
If ActiveSheet.Range("F10").Value2 = "Return from leave" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
Note:
1. Avoid using ActiveWorkbook and ActiveSheet, suggest to replace all instances of them by: ThisWorkbook and datasheet respectively.
2. Additionally, I would suggest to review and incorporate the use of With statement and Select Case statement throughout your procedure.
I'm working on macro for MacBook for separating codes that we paste in file.
After running codes should show up in a folder on my desktop called Tour Codes.
However, file is not getting saved and macro shows error.
I've tried multiple adjustments and changing location of file but the problem remains.
I would appreciate any suggestions.
Sub create_files()
Application.ScreenUpdating = False
Dim iName, iPath
iName = GetUserNameMac
'Get Path and Workbook Name
'iPath = ActiveWorkbook.Path
iPath = "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
Sheets("Data").Select
...
'create files
Dim r1, ddate, gate, id, cap, firstrow, rowcount, newcode
r1 = 2
firstrow = 2
...
Application.DisplayAlerts = False
'save file
ChDir "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
ActiveWorkbook.SaveAs Filename:= _
iPath & ":" & id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv", _
FileFormat:=xlCSV, CreateBackup:=False
'ActiveWorkbook.SaveAs iPath & ":" & merchWk
'ActiveWorkbook.SaveAs iPath & "/" & merchWk
Windows("Gate 1 codes macro.xlsm").Activate
'copy rows to file
'Rows(firstrow & ":" & firstrow + rowcount - 2).Select
Range(Cells(firstrow, 1), Cells(firstrow + rowcount - 2, 1)).Select
Selection.Copy
Windows(id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv").Activate
'Cells(2, 1).Select
Cells(1, 1).Select
ActiveSheet.Paste
'Columns("A:E").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
'save file
Cells(1, 1).Select
ActiveWorkbook.Save
ActiveWindow.Close
Application.DisplayAlerts = True
Windows("Gate 1 codes macro.xlsm").Activate
firstrow = r1 - 1
r1 = firstrow
Loop Until r1 > lastrow
End Sub
Function GetUserNameMac() As String
Dim sMyScript As String
sMyScript = "set userName to short user name of (system info)" & vbNewLine & "return userName"
GetUserNameMac = MacScript(sMyScript)
End Function
VBA errors out on these lines:
Very new to VBA and trying to create an automated textfile export.
Currently it works like a charm for row 1 and the textfile is created. But when adding data on row 2 as well I get:
Runtime error 91, Object variable or With block variable not set.
Any help would be much appreciated!
Sub Exportera()
Dim bKlar As Boolean
Dim bSkrivPSlut As Boolean
Dim bSkrivPStart As Boolean
Dim fsoExpFil As FileSystemObject
Dim fsoTextStream2 As TextStream
Dim sExportFile As String
Dim iSvar As Integer
Dim iSvar2 As Integer
Dim sSokvag As String
Dim sFilnamn As String
Dim sTemp As String
Dim sPFalt As String
Dim cVarde As Currency
Dim sDatum As String
'alright då skapar vi fil och skriver till den
Set fsoExpFil = New FileSystemObject
Range("K10").Select
sSokvag = Trim(ActiveCell.FormulaR1C1)
Range("K13").Select
sFilnamn = Trim(ActiveCell.FormulaR1C1)
If Not UCase(Right(sFilnamn, 4)) = ".TXT" Then
sFilnamn = sFilnamn & ".txt"
End If
sExportFile = sSokvag & "\" & sFilnamn
If sSokvag = "" Or sFilnamn = "" Then
MsgBox "Exporten avbryts då sökväg och filnamn saknas för exportfilen.", vbInformation, sAppName
Exit Sub
Else
If fsoExpFil.FileExists(sExportFile) = True Then
iSvar = MsgBox("Filen " & sFilnamn & " finns redan, skall den ersättas?", vbYesNo, sAppName)
If iSvar = vbNo Then
Exit Sub
End If
Else
iSvar = MsgBox("Är du säker att du vill exportera?", vbYesNo, "Exportera")
End If
End If
If iSvar = vbYes Then
Set fsoTextStream2 = fsoExpFil.OpenTextFile(sExportFile, ForWriting, True)
fsoTextStream2.WriteLine "Filhuvud"
fsoTextStream2.WriteLine vbTab & "Typ=" & """Anställda"""
sTemp = "SkapadAv=" & """"
sTemp = sTemp & "Importfil"
sTemp = sTemp & """"
fsoTextStream2.WriteLine vbTab & sTemp
fsoTextStream2.WriteLine vbTab & "DatumTid=" & "#" & Now & "#"
bKlar = False
i = 1
Sheets("Data").Select
While bKlar = False
i = i + 1
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
If IsNumeric(ActiveCell.FormulaR1C1) Then
fsoTextStream2.WriteLine "PStart"
fsoTextStream2.WriteLine " Typ = ""Anställda"""
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
fsoTextStream2.WriteLine " Anställningsnummer = " & ActiveCell.FormulaR1C1
End If
Range("B" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Namn=" & Trim(ActiveCell.FormulaR1C1)
End If
Range("D" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Utdelningsadress=" & ActiveCell.FormulaR1C1
End If
Range("E" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " co_adress=" & ActiveCell.FormulaR1C1
End If
Range("G" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postadress=" & ActiveCell.FormulaR1C1
End If
Range("F" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postnummer=" & ActiveCell.FormulaR1C1
End If
Range("C" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
sTemp = Mid(sTemp, 1, 6) & "-" & Mid(sTemp, 7)
fsoTextStream2.WriteLine " Personnummer=" & sTemp
End If
Range("H" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " E_mail=" & ActiveCell.FormulaR1C1
End If
Range("I" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
Range("AM" & i).Select
sTemp = sTemp & ActiveCell.FormulaR1C1
sTemp = Replace(sTemp, "-", "")
fsoTextStream2.WriteLine " Bankkontonummer=" & sTemp
End If
Range("J" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sDatum = ActiveCell.Text
fsoTextStream2.WriteLine " Anställningsdatum=" & "#" & sDatum & "#"
End If
fsoTextStream2.WriteLine "PSlut"
fsoTextStream2.Close
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
End If
End Sub
Your problem is not exactly what you'd be expecting.
Note that in your while loop, you close your filestream object at the end with fsoTextStream2.Close. What you'll be seeing is that it will successfully write the first line, but then close the file and then try to write to a file that is closed.
Simply moving this outside the loop (after wend) will fix your problem (Shown below).
fsoTextStream2.WriteLine "PSlut"
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
fsoTextStream2.Close 'This line has been moved outside the loop
End If
End Sub
There's quite a few improvements for your code, if you alter it slightly to avoid .select calls. Also .value rather than .text might be useful if your cells have numeric input. Note that you can extract cell values without having them selected by using range("A" & i).value (or simply range("A" & i)) using worksheet("sheetname").range("A" & i) to access specific sheet cells. (cells(row, column) works just as well).
I'm trying to copy a lot of workbooks into a summary workbook, I've gotten the below code to do the job so far.
Option Explicit
Const FOLDER_PATH = "Folderpath\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = Sheets("Status").Cells(Rows.Count, "AK").End(xlUp).Row + 1
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
'On Error GoTo errHandler
'Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Status")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets("Side 1-Forside") 'EDIT IF NECESSARY
'import the data
With wsTarget
.Activate
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C15").Copy
.Range("B" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C13").Copy
.Range("C" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I11").Copy
.Range("J" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I10").Copy
.Range("K" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C40").Copy
.Range("L" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("E40").Copy
.Range("M" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I9").Copy
.Range("H" & rowTarget).Select
ActiveSheet.Paste Link:=True
'optional source filename in the last column
.Range("AK" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
'errHandler:
'On Error Resume Next
'Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
However is it possible to grab the data as a link instead of a "dead" value? So if it gets changed in one of the many workbooks, I just have to refresh the summary workbook?
Bonusquestion: Is it possible to check for duplicates in this bit: .Range("AK" & rowTarget).Value = sFile and only add if the values isn't there already and the new values should add from the last empty row below row 5?
You could copy the source range and then use Special Paste › Paste Link in the destination workbook. It pastes a formula linking to the source workbooks copied range.
This short YouTube video should illustrate it best.
You could also do that with VBA if necessary e.g:
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Select
ActiveSheet.Paste Link:=True
It seems like we need to .Select first and use ActiveSheet.Paste otherwise the link pasting fails, even if that looks like a bad practice, but the below direct referencing the range won't work!
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Paste Link:=True 'fails with error 438
But because you are linking the values now with a formula you probably need to do that only once and therefore don't need the VBA solution anymore, because it is easier to do it once by hand.
Note:
be aware that these workbooks are linked by a formula then. If you move the source workbook into another location the link will break (if the destination workbook is not within the same location and copied as well). This comes with all the downsides of linked workbooks.
//edit
With wsTarget
.Activate
.Range("A" & rowTarget).Select
wsSource.Range("C14").Copy
.Paste Link:=True
.Activate
.Range("B" & rowTarget).Select
wsSource.Range("C15").Copy
.Paste Link:=True
Alternative solution to the one suggested by Peh, both work, though the one below is not as flexible but hardcoded instead. Thought I would share.
Option Explicit
Const FOLDER_PATH = "Folderpath\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = Sheets("Status").Cells(Rows.Count, "AK").End(xlUp).Row + 1
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
'On Error GoTo errHandler
'Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Status")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'import the data
With wsTarget
'optional source filename in the last column
.Range("AK" & rowTarget).Value = sFile
.Range("A" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$14"
.Range("B" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$15"
.Range("C" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$13"
.Range("J" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$11"
.Range("K" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$10"
.Range("L" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$40"
.Range("M" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$E$40"
.Range("H" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$9"
End With
'close the source workbook, increment the output row and get the next file
rowTarget = rowTarget + 1
sFile = Dir()
Loop
'errHandler:
'On Error Resume Next
'Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
Try this AddIn. It will do exactly what you want.
https://www.rondebruin.nl/win/addins/rdbmerge.htm