Can GetObject do this? - vba

I'm currently working on developing a macro that will input various forms into an access database.
Due to the nature of the beast of this program, I've had to split my main program into two sub programs and call them, but I need to use getobject to call a file path twice now.
I use getobject to open a file, and then use myrec.fields(~column name~) = xlsht.cells(1, "a") to populate various column values. I'm unsure if there are other "efficient" ways to accomplish this.
I was wondering if it is possible to use a variable in place of the filepath with the GetObject command, instead of needing to manually replace the file path in the code.
I've tested a fair amount of different code, including the path, class functionality but I don't think I understand VBA enough to truly make the best use of that.
I can make it work using this
Dim XL As Variant
Dim XLApp As Variant
Dim XLsht As Variant
Dim XLwrkbk As Variant
Set XL = CreateObject("Excel.Application")
Set XLwrkbk = GetObject(~file path~)
Set XLsht = XLwrkbk.Worksheets(1)
Set MyRec = CurrentDb.OpenRecordset("database name")
Ideally I would like it to be
Dim filename As String
Dim XL As Variant
Dim XLApp As Variant
Dim XLsht As Variant
Dim XLwrkbk As Variant
filename = " ~insert file path~ "
Set XL = CreateObject("Excel.Application")
Set XLwrkbk = GetObject(filename)
Set XLsht = XLwrkbk.Worksheets(1)
Set MyRec = CurrentDb.OpenRecordset("database name")
I receive a run time error
Run-time error '5':
Invalid procedure call or argument.

Try something like this:
Dim XL As New Excel.Application, Filename As String
Filename = "~ your file ~"
XL.Workbooks.Open (Filename)
myrec.fields(~column name~) = XL.Worksheets(1).Range("A1").value

Related

Interop - save UTF-8 .csv to .xlsx

Using Excel.Interop I want to open a .txt or .csv file and save it as an excel file. Most of the times this simple code works:
Dim Exl As New Excel.Application()
Dim wb1 As Excel.Workbook = Exl.Workbooks.Open("C:\MyFile.txt", Format:=4)
wb1.SaveAs("C:\MyFile.xlsx", FileFormat:=Excel.XlFileFormat.xlOpenXMLWorkbook)
wb1.Close()
Exl.Quit()
However sometimes the .txt/.csv that is being converted contains special characters like ü, ä or ö - and in these cases these characters are replaced by other characters in the resulting excel file.
The problem seems to be that the input files are UTF-8 encoded. So I tried to change the second line to
Dim wb1 As Excel.Workbook = Exl.Workbooks.Open("C:\MyFile.txt", Format:=4, Origin:=61005)
which doesn't work either.
Another option that I came across was to simply use OpenText instead of Open, however now I get an exception:
Dim wb1 As Excel.Workbooks
wb1.OpenText("C:\MyFile.txt")
Exl.wb1.SaveAs("C:\MyFile.xlsx", FileFormat:=Excel.XlFileFormat.xlOpenXMLWorkbook)
wb1.Close()
Exl.Quit()
Thank you for any help!
The Origin parameter of the Workbooks.Open Method must be a value from the XlPlatform enumeration;
Name Value Description
xlMacintosh 1 Macintosh
xlMSDOS 3 MS-DOS
xlWindows 2 Microsoft Windows
Your code:
wb1 As Excel.Workbook = Exl.Workbooks.Open("C:\MyFile.txt", Format:=4, Origin:=61005)
is trying to specify a code page identifier. This is supported by the Origin parameter of the Workbooks.OpenText Method. Additionally, you have a transcription error in the identifier value; it should be 65001 not 61005.
Here is an example using then OpenText method.
Sub Example()
Const UTF8CodePage As Int32 = 65001
Dim app As New Excel.Application
app.Visible = True
Dim filePath As String = "F:\TestUTF_8Quoted.txt"
Dim fi As New IO.FileInfo(filePath)
app.Workbooks.OpenText(Filename:=filePath, Semicolon:=True, Origin:=UTF8CodePage, TextQualifier:=Excel.XlTextQualifier.xlTextQualifierDoubleQuote)
Dim wb As Excel.Workbook = app.Workbooks.Item(fi.Name)
wb.Close(False)
app.Quit()
End Sub

Method open of object workbooks failed error

When Im executing this code i'm getting an error [Run-time error '1004': Method 'Open' of object 'Workbooks' failed.
I read online that this might be an error with the actual file so I also tried using "IgnoreReadOnlyRecommended:=True" to allow the file to repair itself but that didn't work either. Any suggestions on how to get around this?
Sub BlueFieldImport()
Dim mywb As Workbook
Set mywb = ThisWorkbook
Dim filepath As String, fp As String
Dim mymonth As String
mymonth = Sheets("Data_Staging").Range("A38").Value
filepath = FindFile("C:\Book1.xls")
Dim BlueFieldsWB As Workbook
Set BlueFieldsWB = Workbooks.Open(filepath, , ReadOnly:=True)
Instead of using variable, just pass the string containing the path.
What is the logic behind function to find the file if you pass it direct path anyway?

Set xWorkb = New workbook not working, ActiveX error

I have some code below, It works like a charm but I'm curious about some things.
Why can't I make a Set xWorkb = new Workbook statement? Instead I use the Dim xWorkb as new Workbook, which works. But I've learned (hopefully correct) that using the new statement within a Dim is bad practice, and that you should create the object seperately. So why doesn't it work? I get a ActiveX component can't create object error, but the xWorkb is still being created later as an object right due to the new statement in the Dim section? Makes me confusing.
Why can't I use the excel.application.workbooks when defining variable xApp? Is it because I have to specify a workbook and can't just leave the workbooks empty like that? I get a type mismatch error when I'm trying to change excel.application to excel.application.workbooks.
Sub tester()
Dim xWorkb As New Workbook
Dim xApp As Excel.Application: Set xApp = New Excel.Application
Dim xFiles_target() As Variant
Dim file_path As String
xFiles_target = Array("Bella.xls", "Fizz.xls", "Milo.xls", "Jake.xls")
file_path = Dir("C:\Users\hans\Desktop\")
Do While Len(file_path) > 0
Debug.Print file_path
If UBound(Filter(xFiles_target, file_path)) >= 0 Then
Debug.Print "found " & file_path
Set xWorkb = xApp.Workbooks.Open("C:\Users\hans\Desktop\" & file_path)
xApp.ActiveSheet.Cells(2, 2) = "tester"
xWorkb.Save
xWorkb.Close
End If
file_path = Dir
Loop
End Sub
You cannot create new workbooks with New because workbooks are coupled with Application and must be created with Workbooks.Add or Workbooks.Open.
Dim xWorkb as new Workbook does not work - it appears to work because you don't access xWorkb between declaring it and assigning it with Workbooks.Open. If you did, you would get the same ActiveX component can't create object error.
The error is because Excel.Workbook does not have any public constructors.
You cannot define a variable as excel.application.workbooks because that is not a type. It is a property named Workbooks, of type Excel.Workbooks, that belongs to an object named Application of type Excel.Application.
You can declare the variable as Excel.Workbooks, but you probably don't want to, because you will need to create an Excel.Application to use it anyway.

'DBNull' Error when attempting to set a range in VB.net. Database is Excel

I've written a pretty useful macro within Excel in VBA and am attempting to transfer it to a stand-alone windows application written in VB.net. I've found all the referencing pretty confusing and am now facing trouble in converting the general syntax of my code.
I'm pasting below the relevant code:
Dim ElevenSheets As Excel.Worksheet
Dim TwelveSheets As Excel.Worksheet
Dim ThirteenSheets As Excel.Worksheet
Dim WorkingSheet As Excel.Worksheet
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("FILENAME.xls") 'Removed file name for company confidentiality purposes.
ElevenSheets = xlWorkBook.Worksheets("2011")
TwelveSheets = xlWorkBook.Worksheets("2012")
ThirteenSheets = xlWorkBook.Worksheets("2013")
WorkingSheet = xlWorkBook.Worksheets("WorkingSheet")
...
Cell = WorkingSheet.Range("B3") '<--- This line causes the error.
CurrentCell = (Cell.Row & "," & Cell.Column)
CurrentRow = Cell.Row
MyColumn = (Cell.Column)
CurrentCell = (CurrentRow & "," & MyColumn)
So, as you can see I've pointed out the line that gives me an error. I'm trying to set a range names "Cell" and the error "MissingMemberException unhandled No default member found for type 'DBNull'" presents itself.
Does anyone know what I've done wrong? I'm sure it's something very simple with my syntax but am finding this whole process difficult and also finding it difficult to understand other reasonably similar topics on the internet.
Thanks for bothering to ready this and let me know if you need more context,
Josh
I dont see any constructor for Cell. Also you dont have to explicitly declare all those worksheets. You can simply call them using something like xlWorkBook("WorkingSheet").Range("B3")
I have fixed the problem through trial and error. The way I did it was simply change these declarations:
ElevenSheets = xlWorkBook.Worksheets("2011")
TwelveSheets = xlWorkBook.Worksheets("2012")
ThirteenSheets = xlWorkBook.Worksheets("2013")
WorkingSheet = xlWorkBook.Worksheets("WorkingSheet")
To this:
ElevenSheets = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)
TwelveSheets = CType(xlWorkBook.Worksheets(2), Excel.Worksheet)
ThirteenSheets = CType(xlWorkBook.Worksheets(3), Excel.Worksheet)
WorkingSheet = CType(xlWorkBook.Worksheets(4), Excel.Worksheet)
I don't know whether changing the sheet names to the sheet number fixed it or the CType fixed it. But one of them did.
Thank-you for your contributions!

overwrite a csv file using vba

There are a number of similar posts but nothing that does exactly what I want as simply as it needs to be for me to understand
I want to use Access 2007 VBA to open a csv file and replace the column headings row ie:
OldColumn1,OldColumn2
1,2
with
NewColumn1,NewColumn2
1,2
ie without disturbing the rump of data.
Then save and close.
I have tried this code, but it deletes my data:
Sub WriteFile()
Dim OutputFileNum As Integer
Dim PathName As String
PathName = Application.ActiveWorkbook.Path
OutputFileNum = FreeFile
Open PathName & "\Test.csv" For Output Lock Write As #OutputFileNum
Print #OutputFileNum, "NewCol1" & "," & "NewCol2"
Close OutputFileNum
End Sub
Import or link to the .csv so that you have the recordset in your Access 2007 databases.
Write a query with NewColumn[x] as an alias for OldColumn[x].
Write vba code to use TransferText functionality or make a macro to do the same to export your query as a .csv file (overwriting the original csv if you want/need).
Obviously, there are plenty of bonus things you could do to automate and reproduce this concept for any number or types of files. But the above solution should work in an all MS Access environment.
Let me know if you would like details on any of these steps.
Further to my earlier comment, please see the method which uses the Excel reference:
Public Sub EditCsv()
Dim xlApp As Object
dim xlWbk As Object
Dim xlWst As Object
Set xlApp = CreateObject("Excel.Application")
Set xlWbk = xlApp.Workbooks.Open ".../Test.csv" 'Amend this to your needs
Set xlWst = xlWbk.Sheets(1)
'This assumes the columns are at the beginning of the file
xlWst.Range("A1") = "My New Column Name"
xlWst.Range("B1") = "My New Second Column Name"
xlWbk.Close -1 'Close and save the file here
xlApp.Quit
Set xlApp = Nothing
Set xlWbk = Nothing
Set xlWst = Nothing
End Sub