Date for VBA not working in Excel 2011? - excel

Here is my code, I am attempting, which works BTW on a PC, but not on a Mac, to run this code and have an excel sheet created, named, add a tab, change the color of said tabs, change the name of said tabs, and then transpose the data while maintaining the format of the cells and width and height of the cells to the new worksheet.
This works, on a PC.... but when I get onto a Mac, it doesn't.
I go into References, and this is what I see.
I see Ref Edit Control, and Microsoft Scripting Runtime are missing. I disabled both, and the script gives me an error here still:
wbBK2.SaveAs Dir & Application.PathSeparator & "Open Order Report -" & Format(Date, "mm-dd-yyyy") & ".xlsx"
The error happens at the (Date, "mm-dd-yyyy") Specifically the Date section. I can't figure out why this is happening honestly. If someone can peruse this and give me an answer and a solution it be greatly appreciated.
The error I get is an Error '9 Subscript Out Of Range I can't see a reason why this error only shows up on a Mac, and not a PC.
Option Explicit
Sub OpenOrderReportExport()
Dim wsJL As Worksheet 'Jobs List
Dim wsPOT As Worksheet 'PO Tracking
Dim wsTNO As Worksheet 'Tel-Nexx OOR
Dim wsDOO As Worksheet 'Dakota OOR
Dim wbBK1 As Workbook 'Open Order Report
Dim wbBK2 As Workbook 'New Workbook
Dim wsWS1 As Worksheet 'Sheet1
Dim wsWS2 As Worksheet 'Sheet2
Dim wsWS3 As Worksheet 'Sheet3
Dim wsWS4 As Worksheet 'Sheet4
Dim CurrentFile As String, NewFileType As String, NewFile As String, Dir As String, lastrow As Long
Set wsJL = Sheets("Jobs List") 'Jobs List
Set wsPOT = Sheets("PO Tracking") 'PO Tracking
Set wsTNO = Sheets("Tel-Nexx OOR") 'Tel-Nexx OOR
Set wsDOO = Sheets("Dakota OOR") 'Dakota OOR
Set wbBK1 = ThisWorkbook
Set wbBK2 = Workbooks.Add 'New Workbook
Set wsWS1 = wbBK2.Sheets("Sheet1") 'Sheet1
Set wsWS2 = wbBK2.Sheets("Sheet2") 'Sheet2
Set wsWS3 = wbBK2.Sheets("Sheet3") 'Sheet3
Application.ScreenUpdating = False ' Prevents screen refreshing.
CurrentFile = ThisWorkbook.FullName
NewFileType = "Excel Files 2007 (*.xlsx)"
Dir = ThisWorkbook.path & Application.PathSeparator & "Reports"
wbBK2.SaveAs Dir & Application.PathSeparator & "Open Order Report -" & Format(Date, "mm-dd-yyyy") & ".xlsx"
Sheets.Add After:=Sheets(Sheets.Count)
Set wsWS4 = wbBK2.Sheets("Sheet4") 'Sheet4
With wbBK2
Dim Sht As Worksheet
For Each Sht In Worksheets
Sht.Tab.Color = 255
Next
End With
Sheets("Sheet1").Name = "Jobs List"
Sheets("Sheet2").Name = "PO Tracking"
Sheets("Sheet3").Name = "Dakota OOR"
Sheets("Sheet4").Name = "Tel-Nexx OOR"
With wbBK1
'Jobs List Export
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("A2:N2").Copy
wsWS1.Range("A1").PasteSpecial xlPasteAll
wsJL.Range("A3:N" & lastrow).Copy
wsWS1.Range("A2").PasteSpecial xlPasteValuesAndNumberFormats
wsWS1.Range("A2").PasteSpecial xlPasteColumnWidths
wsJL.Range("B3:N" & lastrow).Copy
wsWS1.Range("B2").PasteSpecial xlPasteFormats
wsWS1.Columns("A").Delete
'Tel-Nexx Export
lastrow = wsTNO.Range("B" & Rows.Count).End(xlUp).Row
wsTNO.Range("A2:Q2").Copy
wsWS2.Range("A1").PasteSpecial xlPasteAll
wsTNO.Range("A3:Q" & lastrow).Copy
wsWS2.Range("A2").PasteSpecial xlPasteValuesAndNumberFormats
wsWS2.Range("A2").PasteSpecial xlPasteColumnWidths
wsTNO.Range("B3:Q" & lastrow).Copy
wsWS2.Range("B2").PasteSpecial xlPasteFormats
wsWS2.Columns("A").Delete
'Dakota Export
lastrow = wsDOO.Range("B" & Rows.Count).End(xlUp).Row
wsDOO.Range("A2:O2").Copy
wsWS3.Range("A1").PasteSpecial xlPasteAll
wsDOO.Range("A3:O" & lastrow).Copy
wsWS3.Range("A2").PasteSpecial xlPasteValuesAndNumberFormats
wsWS3.Range("A2").PasteSpecial xlPasteColumnWidths
wsDOO.Range("B3:O" & lastrow).Copy
wsWS3.Range("B2").PasteSpecial xlPasteFormats
wsWS3.Columns("A").Delete
'PO Tracking Export
lastrow = wsPOT.Range("B" & Rows.Count).End(xlUp).Row
wsPOT.Range("A2:K2").Copy
wsWS4.Range("A1").PasteSpecial xlPasteAll
wsPOT.Range("A3:K" & lastrow).Copy
wsWS4.Range("A2").PasteSpecial xlPasteValuesAndNumberFormats
wsWS4.Range("A2").PasteSpecial xlPasteColumnWidths
wsPOT.Range("B3:K" & lastrow).Copy
wsWS4.Range("B2").PasteSpecial xlPasteFormats
wsWS4.Columns("A").Delete
End With
With wsWS1
.Activate
.Range("A1").Select
End With
End Sub

the MISSING references are what are causing the problems. Remove the checkmarks there, and the basic stuff like date will start working again. If those references are critical to the code you are running, you will have to search out the Mac equivalents
More about references - normally resolving "Missing" fixes it, but, from here
What you're describing is typical of corrupted references. This can
be caused by a referenced file being a different version or in a different
location between the machine on which the code was developed, and the
client machines. Our company also tries to keep all the machines configured
the same way, but I've found it's essentially impossible to manage.
Open any code module (or open the Debug Window, using Ctrl-G, provided you
haven't selected the "keep debug window on top" option). Select Tools |
References from the menu bar. Examine all of the selected references.
If any of the selected references have "MISSING:" in front of them, unselect
them, and back out of the dialog. If you really need the reference(s) you
just unselected (you can tell by doing a Compile All Modules), go back in
and reselect them.
If none have "MISSING:", select an additional reference at random, back out
of the dialog, then go back in and unselect the reference you just added. If
that doesn't solve the problem, try to unselect as many of the selected
references as you can (Office may not let you unselect them all), back out
of the dialog, then go back in and reselect the references you just
unselected. (NOTE: write down what the references are before you delete
them, because they'll be in a different order when you go back in)
Yes, disambigulating as VBA.xxxx will work, since Excel no longer has to
look through all of the references.

Related

Save used range as jpg to SharePoint online with variable name

I have been trying for a while now to edit different code pieces found online to save only the used range of my active workbook as a jpg to my SharePoint online directory. I managed to make a VBA Code work that saves the range as a jpg in a local path but when I change this path to my SharePoint online link it only opens my file explorer and asks me to SaveAs.
I am very new to VBA so I basically have no experience and would therefore be very thankful for any help. Below the VBA Code that does not work right now.
I am pretty sure that the issue lies within the ExportName= ... and ChO.Chart.Export since I took this part from a code that SavesAs to a local path. But like mentioned before I am very new to VBA and therefore have no idea how to recode this to my use case.
Sub SaveAsJPG()
Dim ChO As ChartObject, ExportName As String
Dim CopyRange As Range
Dim Pic As Picture
Dim i As Long
Dim SharePointAdress As String
'My SharePoint Online Adress
SharePointAdress = "https://xxxxxx.sharepoint.com/sites/xxxxx/Shared Documents" & "/"
With ActiveSheet
Set CopyRange = .UsedRange
If Not CopyRange Is Nothing Then
Application.ScreenUpdating = False
ExportName = Application.GetSaveAsFilename(InitialFileName:=SharePointAdress & .Range("A1") & "_" & .Range("J1"), FileFilter:="JPEG Files (*.jpg), *.jpg")
If Not ExportName = "False" Then
CopyRange.Copy
.Pictures.Paste
Set Pic = .Pictures(.Pictures.Count)
Set ChO = .ChartObjects.Add(Left:=10, Top:=10, Width:=Pic.Width, Height:=Pic.Height)
Application.CutCopyMode = False
Do
DoEvents
Pic.Copy
DoEvents
ChO.Chart.Paste
DoEvents
i = i + 1
Loop Until (ChO.Chart.Shapes.Count > 0 Or i > 50)
ChO.Chart.Export Filename:=ExportName, Filtername:="JPG"
ChO.Delete
Pic.Delete
End If
Application.ScreenUpdating = True
End If
End With
End Sub
Range A1 & J1 have the name of the Table & the current calender week inside (so the filename is variable). I do not have the option to connect the SharePoint Link to the network folders.
Thank you for any help for a newbie! :)

Problems with saving excel file after importing data via macro

I want to insert data from source files in my excel model by opening the files and copying and pasting the values. I am just updating the values and not inserting formulas, formats or images etc.
The macro works fine and the inputs are pasted in my excel model. The last command is: ActiveWorkbook.Save
However, sometimes the macro cannot save the file (and I cannot see a regularity here - sometimes it works, sometimes it doesn't) and it displays the error message: "Errors were detected while saving. Microsoft Excel may be able to save the file by removing or repairing some features. To make the repairs in a new file, click continue. To cancel saving the file, click cancel."
Does anyone have an idea on how to fix this error? I am also posting the full code below. Thanks a lot in advance!
' Definitions
Dim i As Integer
Dim mapping_sheet, Worksheet_MVP, Dateiname_Input, Name_Worksheet_Input, Pfad_Input, Pfad_Datei, Zelle, Text As String
' Workbooks
Dim MVP, Auszug As Workbook
Pfad_Input = ActiveSheet.Range("B7").Value
Set MVP = ActiveWorkbook
Sheets("Automatisierung Datenupdate").Activate
Workbooks(MVP.Name).Application.Calculation = xlCalculationManual
Workbooks(MVP.Name).Application.CalculateBeforeSave = False
' 1. Updating Macro
' Copy Pasting Data
If ActiveSheet.Range("E11").Value = "Ja" Then
Dateiname_Input = ActiveSheet.Range("M11").Value
Name_Worksheet_Input = ActiveSheet.Range("D11").Value
Worksheet_MVP = ActiveSheet.Range("B11").Value
Pfad_Datei = Pfad_Input & "\" & Dateiname_Input
Sheets(Worksheet_MVP).Activate
Range("B6:ZZ300").Select
Selection.ClearContents
Set Auszug = Workbooks.Open(Filename:=Pfad_Datei)
Workbooks(Auszug.Name).Activate
Sheets(Name_Worksheet_Input).Activate
Range("A4:ZY298").Select
Selection.Copy
Workbooks(MVP.Name).Activate
Sheets(Worksheet_MVP).Activate
Range("B6").Select
Selection.PasteSpecial Paste:=xlPasteValues
' Close and Save
Workbooks(Auszug.Name).Activate
ActiveSheet.Range("A1").Copy
Workbooks(Auszug.Name).Close savechanges:=False
Workbooks(MVP.Name).Activate
Sheets("Automatisierung Datenupdate").Activate
Range("M11").Select
Selection.Copy
Range("C11").Select
Selection.PasteSpecial Paste:=xlPasteValues
End If
' Save
Sheets("Automatisierung Datenupdate").Activate
Application.ScreenUpdating = True
ActiveWorkbook.Save
End Sub
You mix up the concepts in your code which probably leads to the unexpected/irregular errors.
If you don't specify a data type (or object type) when you dim, the variable is Variant by default. e.g. "Dim MVP" is the same as "Dim MVP as variant"
You do assign your workbooks/worksheets to a variable but don't use the magic. Once set you can just refer to the workbook by referencing the varName.
Although variables are very powerfull, when you just want to use cell values it's better to store these in memory (e.g. an array)
Hereunder an alternative approach, only using the named workbooks/worksheets and minimising the interactions with the sheet by using arrays:
Sub ceci()
'dim vars to specific datatype
Dim wb As Workbook, sh As Worksheet, arr
Set wb = ThisWorkbook
Set sh = wb.Sheets("Automatisierung Datenupdate")
'To minimize the interactions with the sheet we store the data in memory, an array
'here we can access each cell by referencing our array(<rowCounter>, <columnCounter>
'e.g. arr(j,i) => if j = 1 and i = 1 we'll have the values of Cell A1
'we can dump these values anywhere in the activesheet, other sheet, other workbook, ..
Dim sh2 As Worksheet, wb2 As Workbook
arr = sh.Range("A1").CurrentRegion.Value2 'assuming you have data as of A1 we store all in the array, you can fine tune if needed though
If arr(11, 5) = "ja" Then 'E11
'source wb
Set sh2 = wb.Sheets(arr(11, 2)) 'b11
sh2.Range("B6:ZZ300").ClearContents
'wb2 - by specifically naming the workbooks and sheets we avoid unexpected errors
Dim sh3 As Worksheet, arr2, Pfad_Datei As String: Pfad_Datei = wb.Path & "\" & arr(11, 13) 'arr(7, 2) & "\" & arr(11, 13) 'b7 & m11
Set wb2 = Workbooks.Open(Filename:=Pfad_Datei)
Set sh3 = wb2.Sheets(arr(11, 4)) 'd11
arr2 = sh3.Range("A4:ZY298").Value2
sh2.Range(sh2.Cells(6, 2), sh2.Cells(UBound(arr2), UBound(arr2, 2))).Value2 = arr2 'dumb to sheet
'wb1
sh.Range("c11").Value = arr(11, 13) 'm11
End If
wb.Save
End Sub

Using Excel VBA to retrieve data from multiple MS Project Files

I have ran into an automation issue that I cannot seem to figure out.
Currently, I have a worksheet,("Project") that contains data in columns "A"(Project Name) & "B"(Project File Location).
Column "B" contains the string location of each MS Project file.
My VBA macro loops through column "B" and opens each MS Project file and copies a task with the .SelectTaskField method and then copies it back into column "E" of the worksheet.
The first 2 projects loop through without any issues, however, on the 3rd project, I receive the Run-time error '1004': An unexpected error occurred with the method.
I co-worker and I have poured through the code and the MS Project Files to see if there are any differences in the data and we cannot find any differences.
Below is a copy of the code that I have been using.
Just wanted to see if anyone else has had similar issues. I have found that MS Project does not like to be manipulated like Excel or Word.
Any help would be greatly appreciated.
Sub Test()
Dim ws As Worksheet
Set ws = Worksheets("Projects")
Dim lrow As Long
lrow = Range("B" & Rows.Count).End(xlUp).Row
'Turns off updates and alerts
Application.ScreenUpdating = True
Application.DisplayAlerts = True
'Select Daily Field Reports and clear worksheet
ws.Range("E2:E" & lrow).ClearContents
'Opens MS Project
Set objproject = CreateObject("MSProject.Project")
'This keeps MS Project invisible. If you want to see it, change to "True"
objproject.Application.Visible = True
Dim oproject As Range
'This cycles through the range and gathers the data for each project
For Each oproject In Range("B2:B" & lrow)
Set objproject = CreateObject("MSProject.Project")
oproject.Select
objproject.Application.FileOpen Selection
objproject.Application.Visible = True
objproject.Application.SelectTaskField Row:=1, Column:="Percent Complete", RowRelative:=False 'The column name must match. This is the only issue that I have uncovered.
objproject.Application.EditCopy
ws.Select
Dim lastrow As Long
lastrow = ws.Cells(Rows.Count, "E").End(xlUp).Row + 1
Dim Rng As Range
Set Rng = ws.Range("E" & lastrow)
'Rng.PasteSpecial xlPasteFormats
Rng.PasteSpecial xlPasteValues
objproject.Application.Quit
Next oproject
'Turns updates and alerts back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
'Closes MS Project
objproject.Application.Quit
End Sub
Using the SelectTaskField method presumes the file was saved in a task view and that the column you want is in the table of the view. Better to get the values you need directly from the Task object.
It appears you are looking for the % Complete value from the first task. In that case use this:
objproject.ActiveProject.Tasks(1).PercentComplete
Here's how it could work in your code. I took the liberty of simplifying it a bit:
Sub Test()
Dim ws As Worksheet
Set ws = Worksheets("Projects")
Dim lrow As Long
lrow = Range("B" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = True
Application.DisplayAlerts = True
ws.Range("E2:E" & lrow).ClearContents
Dim objproject As MSProject.Application
Set objproject = CreateObject("MSProject.Application")
objproject.Application.Visible = True
Dim oproject As Range
For Each oproject In Range("B2:B" & lrow)
objproject.FileOpen Name:=oproject.Value, ReadOnly:=True
oproject.Offset(, 3) = objproject.ActiveProject.Tasks(1).PercentComplete
objproject.FileCloseEx
Next oproject
Application.ScreenUpdating = True
Application.DisplayAlerts = True
objproject.Quit
End Sub
Note that it is more straight-forward to get a reference to the application object rather than a child of that object: CreateObject("MSProject.Application") is preferable to CreateObject("MSProject.Project").

Save a specific sheet as individual xls file with vba

I'm trying to write a vba code to save a specific worksheet as another workbook file. I want the user to be able to name the workbook file and path.
I tried different approaches but none of them worked.
If that's not possible, I'm ok with only saving to this location:
"Q:\Sorular\"
Spesific filename is shown in codes.
Sub Soru_Publish()
Dim fName1 As String
fName1 = Worksheets("Storyboard").Range("E3").Value & "_" & Worksheets("Storyboard").Range("E2").Value
Worksheets("Soru_Publish").Visible = True
Worksheets("Soru_Publish_2").Visible = True
Worksheets("Soru_Publish").Activate
Dim FirstBlankCell As Long, rngFound As Range
With Sheets("Soru_Publish")
Set rngFound = .Columns("A:A").Find("*", After:=.Range("A1"), _
searchdirection:=xlPrevious, LookIn:=xlValues)
If Not rngFound Is Nothing Then FirstBlankCell = rngFound.Row
End With
Worksheets("Soru_Publish").Range("A1:Y" & FirstBlankCell & "").Copy
Worksheets("Soru_Publish_2").Range("A1:Y" & FirstBlankCell & "").PasteSpecial Paste:=xlPasteValues
Worksheets("Soru_Publish_2").Copy
With ActiveWorkbook
.SaveAs filename:="Q:\Sorular\" & filename
.Close
End With
Worksheets("Sorular").Activate
Worksheets("Sorular").Range("B4").Select
Worksheets("Soru_Publish").Visible = False
Worksheets("Soru_Publish_2").Visible = False
End Sub
Unfortunately when I run the macro, I get Run-time error '1004' at SaveAs line.
Your code works, but using ActiveWorkbook can give you unexpected results.
If you want to save a single sheet as a new .xls file, just use .SaveAs directly on the sheet you need to save, like this:
Dim wrkSheet As Worksheet
Set wrkSheet = Worksheets("Soru_Publish_2")
wrkSheet.SaveAs Filename:="Q:\Sorular\" & fName1
Or like this if you don't want to define a new variable:
Worksheets("Soru_Publish_2").SaveAs Filename:="Q:\Sorular\" & fName1
Hope this helps.
Sorry, I forgot to change the " filename " to " fName1".
Code works just fine, it was just a typo.

VBA code from Excel 2003 does not work properly in Excel 2010 / 2013

I am really new to VBA but I have managed to write some code basing on examples mainly from this site.The piece of code is supposed to copy data from multiple csv files into one xls file (and then to rename the source csv files). While it works fine in Excel 2003, it does not work so well in Excel 2010 / 2013 (I could not test it in E2007). It appears to stop after copying data from the first csv file into xls file, so after this line:
Range("B4:AZ" & LR).Copy wbDEST.Sheets("Data").Range("B" & NR)
with Error 1004 "Application-defined or Object-defined error". Debugger highlights the next line, i.e.
NR = wbDEST.Sheets("Data").Range("B" & Rows.Count).End(xlUp).Row + 1
I just cannot see what is wrong with it as the same line is used at the beginning of the code and does not stop there.
I would appreciate your advice.
And here is the whole code:
Option Explicit
Sub ImportData()
Dim fPATH As String, fNAMEcsv As String, fNAMEbak As String
Dim LR As Long, NR As Long
Dim wbSOURCE As Workbook, wbDEST As Workbook
Set wbDEST = Workbooks.Open("C:\Utility\Data.xls")
NR = wbDEST.Sheets("Data").Range("B" & Rows.Count).End(xlUp).Row + 1
fPATH = "C:\Utility\DataFiles\" 'remember the final \ in this string
fNAMEcsv = Dir(fPATH & "*.csv") 'get the first filename in fpath
Do While Len(fNAMEcsv) > 0
Set wbSOURCE = Workbooks.Open(fPATH & fNAMEcsv, Local:=True) 'open the file
LR = Range("B" & Rows.Count).End(xlUp).Row 'how many rows of info?
If LR > 1 Then
Range("B4:AZ" & LR).Copy wbDEST.Sheets("Data").Range("B" & NR)
NR = wbDEST.Sheets("Data").Range("B" & Rows.Count).End(xlUp).Row + 1
End If
wbSOURCE.Close False 'close data workbook
fNAMEbak = fNAMEcsv & ".bak" 'rename imported file to .bak
Name (fPATH & fNAMEcsv) As (fPATH & fNAMEbak)
fNAMEcsv = Dir 'get the next filename
Loop
MsgBox ("Completed. Check results on PRINTOUT sheet.")
End Sub
Try qualifying your Rows:
NR = wbDEST.Sheets("Data").Range("B" & wbDEST.Sheets("Data").Rows.Count).End(xlUp).Row + 1
The problem could be this:
Here you open a new "source" workbook wbSOURCE:
Set wbSOURCE = Workbooks.Open(fPATH & fNAMEcsv, Local:=True) 'open the file
Maybe it is a workbook in the "new" format (Excel 2007 and later, *.xlsx & Co.). Since you just opened it, it is the active workbook, and therefore the unqualified Rows.Count will return 1048576.
And maybe your destination workbook wbDEST is in the "old" Excel 2003 format (*.xls & Co.). So when you say this:
NR = wbDEST.Sheets("Data").Range("B" & Rows.Count).End(xlUp).Row + 1
you're trying to access wbDEST.Sheets("Data").Range("B" & 1048576) but cell B1048576 doesn't exist in this 2003-format workbook. This will indeed throw an Error 1004 "Application-defined or Object-defined error".
The solution would then be to fully qualify Rows.Count like this:
NR = wbDEST.Sheets("Data").Range("B" & wbDEST.Sheets("Data").Rows.Count).End(xlUp).Row + 1
It's always a good idea to fully qualify everything and not let it depend on the vagaries of Excel.

Resources