Subscript out of range (Error 9) for importing data - excel

I need to copy two seperate colums of data from one workbook to another.
Here is my code:
Workbooks.Open Filename:=file & "\GSP - " & months(numMonth) & " 1-" & numdays (numMonth) & " " & tYear & " - Prem.xls", _
Origin:=xlWindows, UpdateLinks:=False, ReadOnly:=True
ActiveWorkbook.Sheets(tDay).Activate
range("AA6:AA40").Select
Selection.Copy
Windows(fileM & ".xls").Activate
Sheets("Summary").Activate
range("C3:C37").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveWorkbook.Close
ActiveWindow.Close
Workbooks.Open Filename:=file & "\GSP - " & months(numMonth) & " 1-" & numdays(numMonth) & " " & tYear & " - Prem.xls", _
Origin:=xlWindows, UpdateLinks:=False, ReadOnly:=True
ActiveWorkbook.Sheets(tDay).Activate
range("AA84:AA118").Select
Selection.Copy
Windows(fileM & ".xls").Activate
Sheets("Summary").Activate
range("H3:H37").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveWorkbook.Close
ActiveWindow.Close
When the macro finishes running, the second copy is not completed and I am left with Error 9 at the break on the second Windows(fileM & ".xls").Activate'

I see a lot of problems with this code. As has been mentioned, you are not defining tDay. I assume this is being defined elsewhere, else you wouldn't be getting as far as you are.
Using ActiveWorkbook should be avoided whenever possible, since it may not always be the workbook that you expect. Much better to create a Workbook variable and assign it to the selected workbook; then use it instead. I suspect this is the cause of your problem -- ActiveWorkbook.Close isn't closing the one you expect.
Next, you are opening the file, copying from it, closing it, and repeating. Why not leave it open?
Next, you don't always need to call .Select in order to take action on a range. You can call .Copy and .PasteSpecial directly from the Range object.
I'm making some assumptions about your intent, but the following code incorporates the suggestions above.
Sub foo()
Dim wkbGSP As Workbook
Dim wkbFileM As Workbook
tday = "sheet1"
Set wkbFileM = Workbooks(fileM & ".xls")
Workbooks.Open Filename:=file & "\GSP - " & months(numMonth) & " 1-" & numdays (numMonth) & " " & tYear & " - Prem.xls", _
Origin:=xlWindows, UpdateLinks:=False, ReadOnly:=True
Set wkbGSP = ActiveWorkbook
wkbGSP.Sheets(tday).Range("AA6:AA40").Copy
wkbFileM.Sheets("Summary").Activate
Range("C3:C37").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wkbGSP.Sheets(tday).Activate
Range("AA84:AA118").Copy
wkbFileM.Sheets("Summary").Activate
Range("H3:H37").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wkbGSP.Close
End Sub

Guessing your tDay value is not found such as out of range or no such sheet number. How do you define this value?

Related

Getting "method saveas of object _workbook failed" error while trying to save an XLS as CSV

I have a weird problem.
I have a piece of VBA code that works perfectly fine. Many of my colleagues use it to create CSV files without problems.
Sub CSV_Tagetik()
Dim newWorkbook As Workbook
Dim vWorksheet As Worksheet
Dim vWorkbook As String
Dim vEntity
Dim vDate As String
vWorkbook = ActiveWorkbook.Name
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
'--------------TGK------------
vEntity = Worksheets("Control").Cells(6, 3)
vRange = Worksheets("Control").Cells(1, 18)
vDate = Worksheets("Control").Cells(4, 3)
Sheets("Journaalpost").Visible = True
Sheets("Journaalpost").Select
ActiveSheet.Range(vRange).AutoFilter Field:=13, Criteria1:="<>0", _
Operator:=xlAnd
Range(vRange).Select
Selection.Copy
Set newWorkbook = Workbooks.Add
newWorkbook.Activate
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
newWorkbook.Sheets(1).Name = vEntity
newWorkbook.SaveAs Filename:=Workbooks(vWorkbook).Path & "\" & vEntity & " Aansluiting Tagetik " & vDate, FileFormat:=xlCSV, _
CreateBackup:=False
newWorkbook.Close
Sheets("Journaalpost").Visible = False
Sheets("Control").Select
Finally:
Application.CutCopyMode = False
Exit Sub
End Sub
But now there is a new colleague for whom the save command
newWorkbook.SaveAs Filename:=Workbooks(vWorkbook).Path & "\" & vEntity & " Aansluiting Tagetik " & vDate, FileFormat:=xlCSV, _
CreateBackup:=False
prompts an error:
Run-time error '1004':
Method 'SaveAs' of object '_Worksheet' failed
I have no idea why. I cannot recreate it in my environment, because for me it works perfectly.
What steps could I take to fix this?
Thank you!

Excel is interpreting date wrong

I have a problem. I have data in this format:
13.3.19 00:23:01
I use a macro to import it to one tab, copy it to another tab, and replace the "." with "/" so it in the correct format. But excel said no and interprets most of the data as text, which is not a problem, I just use datevalue on that. But when it comes to this date in particular:
12.3.19 23:52:41
Excel is interpreting it as a date in the US format and instead of leaving it as march the 12th, it makes December the 3rd out of it. This renders the datevalue useless in just a part of my data set.
Any thoughts?
Code of the macro here:
Sub import_data()
Path = Worksheets("Macro").Cells(6, 4).Value
Analysis = ThisWorkbook.Name
Rfrom = Sheets("Macro").Cells(8, 4)
Rto = Sheets("Macro").Cells(9, 4)
Application.DisplayAlerts = False
For Data_Range = Rfrom To Rto
Fname = Sheets("Macro").Cells(Data_Range, 3)
Segment_name = Sheets("Macro").Cells(Data_Range, 4)
'selecting workbook
Workbooks.Open Filename:= _
Path & "\" & Fname _
Sheets(Segment_name).Select
Range("A2:W14000").Select
Selection.Copy
Windows(Analysis).Activate
Sheets("Raw_data_import").Select
Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows(Fname).Activate
ActiveWindow.Close
Windows(Analysis).Activate
Next Data_Range
Windows(ThisWorkbook.Name).Activate
Sheets("Raw_data_import").Activate
Range("E:G").Select
Selection.Copy
Sheets("Priprava_dat").Select
Range("A:C").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Priprava_dat").Range("A:B").Replace ".", "/"
Dim lastRow As Long
lastRow = Range("C" & Rows.Count).End(xlUp).Row
Range("D2").AutoFill Destination:=Range("D2:D" & lastRow)
Range("E2").AutoFill Destination:=Range("E2:E" & lastRow)
Range("F2").AutoFill Destination:=Range("F2:F" & lastRow)
Range("G2").AutoFill Destination:=Range("G2:G" & lastRow)
Range("H2").AutoFill Destination:=Range("H2:H" & lastRow)
Range("I2").AutoFill Destination:=Range("I2:I" & lastRow)
Range("J2").AutoFill Destination:=Range("J2:J" & lastRow)
Windows(ThisWorkbook.Name).Activate
Sheets("Macro").Activate
End Sub
you can set the number format of the cells using
Sheets("Priprava_dat").Range("A:B").NumberFormat = "dd/mm/yy hh:mm:ss"
just before changing the '.' to '/' using
Sheets("Priprava_dat").Range("A:B").Replace ".", "/"

Pastespecial pasting only the first cell value across entire range

I'm trying to paste the formula results from one column to the next. I need to perform this through a macro without using a loop as it slows down the tool due to large number of records. The following methods are not working -
a) range("G5:G10").value = range("H5:H10").value
b) Selection.PasteSpecial paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
The issue is that excel copies the formula result of the first cell ("G5") to all the cells at the destination ("H5:H10"). The formula in the source is an array formula. Could anyone please share how to resolve the issue.
Edit :
Sub paste()
'
' paste Macro
'
'
Dim ColName As String, sheetname1 As String, lookup_col As String, lastrow_range As Long
ColName = "A"
sheetname1 = "Sheet1"
lookup_col = "C"
lastrow_range = 8
Worksheets("Sheet1").Range("F5").Select
ActiveCell.FormulaArray = _
"=IF(ISERROR(MATCH(TRUE,EXACT($" & ColName & ActiveCell.Row & "," & sheetname1 & "!$" & lookup_col & "$5:$" & lookup_col & "$" & lastrow_range & "),0)) , ""-" & ColName & """&"" is Invalid. This should match with any one of the values in column "" &""" & lookup_col & """&"" of "" & """ & sheetname1 & """&"". Please refer ""&""" & sheet_name & """ ,""It Matches"")"
Worksheets("Sheet1").Range("F5").Select
Selection.AutoFill Destination:=Range("F5:F8")
Range("F5:F8").Select
Selection.Copy
Range("G5").Select
Selection.PasteSpecial paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End Sub
Copy and paste special values of range
Range("H5:H10").Copy
Range("G5:G10").PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
Copy and paste range
Range("H5:H10").Copy
Range("G5:G10").PasteSpecial (xlPasteAll)
Application.CutCopyMode = False
Or copy and paste the entire column
Range("H:H").Copy
Range("G:G").PasteSpecial (xlPasteAll)
Application.CutCopyMode = False
Thanks for the input.
I found that the calculation method had to be changed to 'Automatic' from 'Manual' :
Application.Calculation = xlAutomatic

Saving In new File using macro in VBA

Im using the following code, but when I run it, it only saves the last part (& Day(Now) & "-" & Month(Now) & "-" & Year(Now)) of the name. Is not taking into consideration de string "Asesor". I don't know what part I'm missing:
Sub SaveFile()
Dim Asesor As String
Asesor = Range("B3").Value
Dim DestFile
DestFile = "C:\Users\ST\"
Application.ScreenUpdating = False
Workbooks("Grillas_QA.xlsm").Activate
ActiveSheet.Range("A1:K51").Select
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
ActiveWindow.DisplayGridlines = False
Application.DisplayAlerts = False
Here's where I save the file.
ActiveWorkbook.SaveAs Filename:=DestFile & Asesor & " " & Day(Now) & "-" & Month(Now) & "-" & Year(Now), _
FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Thnx in advance for the help.
As follow up from comments, next line
Asesor = Range("B3").Value
should be changed to something like this:
Asesor = ThisWorkbook.Worksheets("Sheet1").Range("B3").Value
Also as a recommendation, I suggest you to read this post: How to avoid using Select/Active statements

Optimize VBA code and get rid of Workbook.activate and range.select?

I've got a macro which copies a code from one workbook to another one. My code is pretty long and I would like to shorten it if possible (also to be a bit more independent from the macro-recorder)
My code looks like this:
Workbooks("export.XLSX").Activate
Range("A2:A" & Range("A" & Rows.Count).End(xlUp).row).Copy
Workbooks("ORDERS.CSV").Activate
Range("X3").Select
Selection.End(xlDown).Offset(1, -18).Select
ActiveSheet.Paste
Workbooks("export.XLSX").Activate
This block repeats itself for different columns. Is there a way to shorten this?
More examples:
Range("C2:C" & Range("A" & Rows.Count).End(xlUp).row).Copy
Workbooks("ORDERS.CSV").Activate
Range("X3").Select Selection.End(xlDown).Offset(1, -14).Select
ActiveSheet.Paste
Workbooks("export.XLSX").Activate
Range("G2:G" & Range("A" & Rows.Count).End(xlUp).row).Copy
Workbooks("ORDERS.CSV").Activate
Range("X3").Select Selection.End(xlDown).Offset(1, -13).Select
ActiveSheet.Paste
Workbooks("export.XLSX").Activate
Firt of all add Application.ScreenUpdating = False
Workbooks("export.XLSX").Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row).Copy
Workbooks("ORDERS.CSV").Range("X3").End(xlDown).Offset(1, -18).Select.PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
and follow the same pattern, then
Application.Screenupdating = True

Resources