Run-time Error 9 w/Variable Workbook Name - vba

So the user is able to import data from another excel file and I want to close the other excel file once the values have been copied into the current workbook. I can't, however, get my code to go back and select the other excel file in order to close it again.
I've already checked and it's only running one instance of Excel.
Option Explicit
Private Sub Button_ImportSubmittedData_Click()
Dim MyFile As String
Dim tempDataSetName As String
tempDataSetName = "Submitted Apps"
MyFile = Application.GetOpenFilename("Excel Files,*.xlsx")
Workbooks.OpenText Filename:=MyFile
ActiveSheet.Range("A2").Select
ActiveSheet.Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Windows("HET.xlsm").Activate
Sheets("Submitted").Select
ActiveSheet.Range("A2").Select
ActiveSheet.Paste
Selection.Columns.AutoFit
ActiveSheet.Range("A1").Select
**Windows(MyFile).Activate**
'Application.DisplayAlerts = False
'ActiveWindow.Close
'Windows("HET.xlsm").Activate
'ActiveSheet.Range("A1").Select
End Sub

Related

run .vbs script from excel

I have macro file and I saved it as a .vbs file called macro.vbs, and here is the location on my local C:Dekstop\macro.vbs. Here is the code inside:
Sub Macro3()
Sheets("vlookup").Select
Range("B5").Select
Selection.EntireColumn.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
Range("B5").Select
ActiveCell.FormulaR1C1 = "Journal classification (name)"
Range("B6").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-1],LW0640!R2C5:R12163C6,2,TRUE)"
Selection.AutoFill Destination:=Range("B6:B6098")
Range("B6:B6098").Select
end sub
What I want to do is, I want to call that .vbs script from my excel file. So I plan to create the button from developer in excel and call that .vbs file.
Is there a way to do it?
To make your work easier you can have a central workbook in which you will put your code along with the code below
Sub test()
Dim file As String
Dim wb As Workbook
file = Worksheets("Sheet1").Range("A1").Value
Set wb = Workbooks.Open(file)
call Macro3
Set wb = Nothing
End Sub
Then in this workbook's Sheet1's cell A1 you can put the full file path of the file to be processed.
You can even have a range of file paths and loop through it.

Need assistance with VBA

I have an import code that works perfectly on my 2013 64bit excel; however, I have users that are using 2010 Excel with 32bit and the code does not work. I would be very grateful if someone would look at the below code and tell me what I need to change in order for my 2010 32bit users to be able to use it:
Sub TransferData()
''<<<<unprotect code
Dim i As Integer
For i = 1 To Sheets.Count
Sheets(i).Unprotect password:="ADMIN"
Next i
'
''<<<<<main code
'
Application.ScreenUpdating = False
Sheets("Dashboard").Activate
Sheets("DASF Data").Range("DASF_Range").ClearContents
'
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ActiveWorkbook
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
If Sheet.Visible = True Then
Range("A2:Y10000").Select
Selection.Copy
Windows("DASF MANAGEMENT TOOL (CONUS Ver 1.0).XLSB").Activate
Sheets("DASF Data").Select
Range("A2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Sheets("Dashboard").Activate
End If
Next Sheet
End If
Workbooks("DASF.XLS").Close SaveChanges:=False
End Sub
That error number does not necessarily have anything specifically to do with your listed code. It could be an error anywhere in your modules: or it could be corrupt code in the compiled version of one of your modules. It could even be a broken library reference.
To exclude the first possibility, do a manual "compile all' of your code.
To fix the second possibility, create a new spreadsheet, and copy the text from your old spreadsheet into new modules in your new spreadsheet. Or download and use an Excel 'decompiler'.

Copy data from a given filename/path vba

I'm trying to create an excel tool where it would extract data from a given filename(workbook). Let's say, on my main workbook in(Sheet1-Cell A1), users will enter the filename. Then on a cmdbutton click, it'll copy the data from that specific filename(workbook).
I have created a file that copies data from another workbook, however, it indicates the specific path & filename of the workbook where the data will be copied.
Dim myData As Workbook
Set myData = Workbooks.Open("C:\Users\Desktop\Book2.xlsx")
Call Sample
Selection.Copy
What I want, is to allow users to just enter the filename, then excel will locate that file, select data from there & copy it on the main workbook(Sheet2).
I figured something out
Sub copydata()
Dim path As String
path = InputBox("Please input path")
Application.ScreenUpdating = False
Dim actualfile As Workbook
Set actualfile = ActiveWorkbook
Dim script As Object
Set script = CreateObject("Scripting.FileSystemObject")
Dim catalogue As Object
Set catalogue = script.GetFolder(path)
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Dim textfile As Object
For Each textfile In catalogue.Files
Workbooks.Open textfile
Dim loadedfile As Workbook
Set loadedfile = ActiveWorkbook
loadedfile.Worksheets(1).Range("A2").CurrentRegion.Offset(1, 0).Copy
actualfile.Worksheets(1).Range("A2").Offset(1, 0).End(xlUp).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
loadedfile.Close Savechanges:=False
Next textfile
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
The only problem though is, it copies data to the column after the heading instead of copying it to the row below the heading - help on this is very much appreciated! :)

'Workbook.open' error - Closes the file right after opening it

I need to get data on one hundred Excel workbooks. I created a macro to loop through those files, get the data and close them. But right after my Workbooks.open(path) opens the file, it closes it and throws a 1004 error saying that the method 'open' failed.
I tried to open another of those one hundred files and every one of them throws the same error. I tried to open a normal file (not one of those one hundred), through the macro, it opens normally.
Copied a bunch of those to my C:\, all of them throw an error.
Recorded a macro to open the file. The file opens because I clicked File->Open File, but it throws an error if I run the macro to open it.
Obviously the problem lies in those files.
LINK to the file.
--> CODE:
Just a normal Workbook.open code (There is no full code, it's just it! And I get an error with the file linked)
Workbook.Open("C:\file.xlsx")
--> They Open normally by hand without any error or problem.
--> They have:
* Querytables
* Normal formulas
* They are kinda small
--> Observations and what I tried:
The paths are right (it opens the file and closes it right after, and error).
The files I'm trying to open have connection queries, but I deleted the connections on my test files. Same error.
Tried the CurruptLoad param, same error (I don't know if I used it right).
Tried UpdateLinks:=0, same error.
Tried to open it through new Excel.Application, nothing changed.
Tried on another PC, same thing.
Anyone had something like this?
What should I try?
What are you doing after the open ?
If you are trying to do something else, then maybe file has not opened completely and error is based on next line not happening.
Solution I found for this case (here in my work)
Application.DisplayAlerts = False
set wb = Workbooks.Open(objFile.path, ReadOnly:=True, CorruptLoad:=xlExtractData)
wb.close
Application.DisplayAlerts = True
Through the CorruptLoad:=xlExtractData, it clear every table, every connection, and anything else that could be problem. I get my data and close the file without saving it.
Thanks for the support guys.
If I understand your problem you can use one code that I use when I need to retrieve data from plus files (all with the same formatting )
Sub ImportData()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim LastRow As Long
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
WsTo = ActiveWorkbook.Name
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then Exit Sub
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Change First Worksheet's Background Fill Blue
Sheets(1).Select
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
WsFrom = ActiveWorkbook.Name
Windows(WsTo).Activate
Sheets(1).Select
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Range("A" & LastRow + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, transpose:=False
Application.CutCopyMode = False
'Save and Close Workbook
Workbooks(WsFrom).Close SaveChanges:=False
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Importazione completata!"
'Reset Macro Optimization Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub

How can I code to close an open workbook using its directory path instead of its name using vba in excel?

So I've written a script that opens a certain workbook using its directory pathway (through text from a userform textbox) and I want to be able to close it at the end of the script.
My script currently opens a workbook using the file directory and copies something from that workbook and pastes it into the current workbook. The only thing I want to add is that workbook closing at the end of the sub.
Sub A()
Dim wbk As Workbook
strFirstFile = Userform1.Command.Text
Set wbk = Workbooks.Open(strFirstFile)
With wbk.Sheets("Sheet1")
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
End With
Set wbk = ThisWorkbook
wbk.Sheets("dog").Range("A1").Insert
End Sub
Bear with me I'm a super newbie.
To close the Workbook:
wbk.Close
If you want to save the workbook beforehand, do:
wbk.Save
wbk.Close