Good day,
I'm trying to insert a pivot table from a table but also add it to a data model via VBA.
I've recorded the process manually and also followed the example of this link: https://powerpivotpro.com/2014/07/adding-tables-to-a-model-from-vba-in-excel-2013/
I change the variables for my data path and workbook name that has been set previously in the code. When I run the macro I get the following error on the first line: "Run-Time error 5: Invalid procedure call or argument".
I've never added a pivot table to a data model via VBA before, thus not sure how the code should look (except what I've seen online and mine seem to adhere to the example)
MainWB.Connections.Add2 "WorksheetConnection_" & MainWB.Name & "!Table_SDCdata", "", _
"WORKSHEET;" & DataPath & "\" & MainWB.Name & ", " & MainWB.Name & "!Table_SDCdata", 7, True, False
MainWB.PivotCaches.Create(SourceType:=xlExternal, SourceData:=MainWB.Connections("WorksheetConnection_" & MainWB.Name & "!Table_SDCdata" _
), Version:=6).CreatePivotTable TableDestination:=wsPivotModel.Name & "!R1C1", TableName:="PvtSDCmodel", DefaultVersion:=6
The variables are as follows: (** added to replace for security in this question, both variables are correct and used many times in the code without problems)
MainWB.name: **2791 SDC Inland 12.08.2020.xlsbCOMBINED.xls
DataPath: C:_Store\Simone_d_drive\Desktop*\2019\Macros*\raw data**\2791\2020.08.16
Any help or point in the right direction will be great thank you!
I managed to find my errors:
Updated code:
MainWB.Connections.Add2 "WorksheetConnection_" & MainWB.Name & "!Table_SDCdata", "", _
"WORKSHEET;" & DataPath & "\" & MainWB.Name, MainWB.Name & "!Table_SDCdata", 7, True, False
I had to remove 2 of the quotation marks, one at the end of the connection string and the 2nd one at the beginning of the command text.
I've a quick question for one of my vba codes , the code is basically consolidating 12 tables into one sheet called temp range B8. The problem is that if I run it using Excel 2016 English version it works fine on any computer but if the excel is 2016 spanish version , it will fail with error: " Execution Error 1004"
I've created 12 modules with macros and only one is failing using the spanish version for the following code
Range("B8").Consolidate Sources:=Array( _
"Enero[#All]", "Febrero[#All]", "Marzo[#All]", "Abril[#All]", "Mayo[#All]", "Junio[#All]", "Julio[#All]", "Agosto[#All]", "Septiembre[#All]", "Octubre[#All]", "Noviembre[#All]", "Diciembre[#All]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
Changing the reference type from #All to #Todo was the fix , I-m good now
I'm glad you found a solution to your problem for the Italian version of Excel.
Perhaps, you could make some changes to your code so it could handle both cases (English and Italian). For instance, you could use the following function that returns the MsoLanguageID for Excel (inspired by this answer):
Function ExcelLanguage() As MsoLanguageID
ExcelLanguage = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
End Function
You could then use an if-statement to handle both cases like this:
If ExcelLanguage = msoLanguageIDItalian Then
Range("B8").Consolidate Sources:=Array( _
"Enero[#Todo]", "Febrero[#Todo]", "Marzo[#Todo]", "Abril[#Todo]", "Mayo[#Todo]", "Junio[#Todo]", "Julio[#Todo]", "Agosto[#Todo]", "Septiembre[#Todo]", "Octubre[#Todo]", "Noviembre[#Todo]", "Diciembre[#Todo]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
Else
Range("B8").Consolidate Sources:=Array( _
"Enero[#All]", "Febrero[#All]", "Marzo[#All]", "Abril[#All]", "Mayo[#All]", "Junio[#All]", "Julio[#All]", "Agosto[#All]", "Septiembre[#All]", "Octubre[#All]", "Noviembre[#All]", "Diciembre[#All]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
End If
For all the MsoLanguageID values, see MSDN Documentation.
This is a continuity question of the below link. https://stackoverflow.com/a/56649098?noredirect=1
I need to do two things
1. Copy all text from PDF and paste it to the excel
2. Copy multiple lines and run a loop to find the text I need
The background of my project - I am opening a webpage with user credentials, after couples of clicks a PDF is opened in the browser. So now I need to get a particular statement from it. The problem is that the PDF is dynamic and the statement I require keeps changing (the line sometimes it is in 6th and sometimes in 9th or 10th and 11th) so the 2 things which I mentioned above will help me I am aware both sounds the same but it is different. Below is the code I used to get a particular statement, but how do I create a loop through all the statement or get multiple statements.
Const statext As String = _
"addEventListener('message',function(e){" & _
" if(e.data.type=='getSelectedTextReply'){" & _
" var txt=e.data.selectedText;" & _
" callback(txt && txt.match(/[^\r\n]+/g)[7]);" & _
" }" & _
"});" & _
"plugin.postMessage({type:'initialize'},'*');" & _
"plugin.postMessage({type:'selectAll'},'*');" & _
"plugin.postMessage({type:'getSelectedText'},'*');"
Casestatus = bot.ExecuteAsyncScript(statext)
I am very new to programming and automation so I may be missing a basic thing. Kindly pardon me.
After browsing forums for well over an hour, I can't seem to figure out why my save as code isn't working.
My goal is to save a new copy of the workbook under a different file type. (The current file type is .csv.) I'm not trying to save in a new or different location, the current directory is where I want it to save to.
I've tried more variations of the following code than I can remember, so I'll just post my current syntax:
CurrentDir = CurDir()
dateVal = Date
ActiveWorkbook.SaveAs Filename:="" & CurrentDir & "ALS Week of " & dateVal - 4 & ".xlsx", FileFormat:=51
I've looked at examples of how to open a dialog box wherein the user inputs information in order to save. But I'm hoping for a hands-off approach. If anyone can see where my error lies, please let me know!
EDIT:
The error that I get is "Method 'SaveAs' of object '_Workbook' failed
Your date has illegal characters in it. Format your date with dashes and not slashes and this won't happen.
The following reserved characters:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
You forgot a backslash:
ActiveWorkbook.SaveAs Filename:= CurDir() & "\ALS Week of " & (Date - 4) & ".xlsx", FileFormat:=51
I have .csv file which is a time series of daily data, with several data points associated with each date.
When I manually open the file, the dates open correctly, as the date format dd/mm/yyyy.
When I open the file programmatically, the dates up to the 12th of each month are opened as mm/dd/yyyy, although the format remains dd/mm/yyyy (e.g. the 1st of July 1983 (1/7/1983), would be opened as the 7th of January 1983 (7/1/1983) - this isn't just a formatting issue, the Julian Date (days since 1 Jan 1901) associated with these dates also changes), and the dates after the 12th of each month are opened correctly, although as text rather than a date.
The data coming in as text is not an issue, however, the dates changing as soon as the file is opened is problematic. I could try to import the entire .csv file as comma delimited text rather than opening the file, however, it would be easier and faster if I could stop the dates from changing when I open the file.
Flder = InputBox("Copy and Paste Folder path here:")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourcePath = FSO.GetFolder(Flder)
For Each File In SourcePath.Files
Workbooks.Open (File)
FlNm = File.Name
StrtCol = Workbooks(FlNm).Worksheets(1).Range(Cells(4, 1), Cells(4, 30)).Find ("Mean").Column
Workbooks(FlNm).Worksheets(1).Range(Cells(1, 1), Cells(60000, 1)).Copy (Workbooks("Find Water Years V2.xls").Worksheets(1).Range("A3"))
Workbooks(FlNm).Worksheets(1).Range(Cells(1, StrtCol), Cells(60000, StrtCol + 1)).Copy (Workbooks("Find Water Years V2.xls").Worksheets(1).Range("B3"))
Workbooks(FlNm).Close
Next
The problem seems to occur at the line Workbooks.Open(File).
Since the question has already been answered by the OP in the comments but not posted as an official answer I'll put it here in case someone else misses it like I did.
workbook = workbooks.Open(filename, Local:= true)
By setting Local = true uses the local machines date format rather than assuming mdy so in locales such as Australia (dmy) it'll change the behavior of Open()
I experienced this problem with Office 365.
With importing an csv file with Excel some dates dd/mm/jjjj (European) where imported as American dates mm/dd/jjjj. The csv file doesn't have any formatting of dates closed in.
By opening as follows:
Set xla = CreateObject("Excel.Application")
Set xlb = xla.Workbooks.Open(sFilePath, ReadOnly:=False, Local:=True)
The local settings where used, and problem solved :-)
Other options with opening a file are:
expression.Open (FileName, UpdateLinks, ReadOnly,
Format, Password, WriteResPassword,
IgnoreReadOnlyRecommended, Origin,
Delimiter, Editable, Notify, Converter,
AddToMru, Local, CorruptLoad)
I could try to import the entire .csv file as comma delimited text rather than actually opening the file, however, it would be easier and faster if I could stop the dates from changing when I open the file.
It is still fast if you open it as CDT. You simply use .OpenText instead of .Open. Rest of the code remains same :)
Try recording a macro and you will see that the code looks somewhat like this.
Workbooks.OpenText Filename:= File, _
Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
TrailingMinusNumbers:=True
I found that user2981639 had the right idea, but I got a syntax error with 'Local: true' so
I used 'local:=True' instead
This problem was driving me nuts because I also had 2 memo fields in the csv file.
If I tried to format the dates in any way the memo fields would not import correctly, they would either be truncated to 255 characters or any embedded CRLF characters would cut the record up into pieces depending on how many there were.
Thanks guys for posting
Here, you see a working code with example. This problem frustrated me as well for a while. I was opening a .txt file in excel and the date I had use for was converting from dd-mm-yyyy format to mm-dd-yyyy format. Below you see a solution. It lay in the last command (,Local := True). See below. Hope it helps.
Note that while trasferring .txt file to excel use File Origin as "xlWindows:
Workbooks.OpenText Filename:= _
ThisWorkbook.Worksheets("Reporting").Cells(3, 6), Origin:=xlWindows, _
StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), Array(49 _
, 1), Array(50, 1), Array(67, 1), Array(80, 1), Array(93, 1), Array(106, 1), Array(119, 1)) _
, DecimalSeparator:=",", ThousandsSeparator:=".", TrailingMinusNumbers:= _
True, Local:=True
NOTE: rest above settings for array and decimal separator are my work specific - may not apply to you.
I am also struggling to find an answer. However what resolves this problem is.:-
Local should be true.
and workbook close save changes must be false. That should work.
Just had this problem myself and found the above solution
workbook = workbooks.Open(filename, Local:= true)
to be problematic in that it generates an error message. The MS documentation doesn't mention brackets or Workbook =, so I used this:-
Workbooks.Open Path, local:=True
Worked form me, hope it helps you.