Open specific Workbook using Userform - vba

I have a folder containing over 100 worksheets and named 1,2,3, etc but I can only open the workbooks by adding .xlsx to the number of the workbook in the combobox.
Is there a way to go around this?
Private Sub CommandButton1_Click()
Dim filename As String
Dim filepath As String
filename = ComboBox1.Value
filepath = "D:\e-library\MSC\DIS7000\data\"
Workbooks.Open (filepath & filename)
End Sub

Yes - you can get through that bu adding .xlsx to the filename programmatically instead of manually.
Try this:
Private Sub CommandButton1_Click()
Dim filename As String
Dim filepath As String
filename = ComboBox1.Value
filepath = "D:\e-library\MSC\DIS7000\data\"
Workbooks.Open (filepath & filename & ".xlsx")
End Sub

Related

Excel VBA - How to write filepath as a variable

I have a file saved in location A with path link C:\User\Testing\A\client_01.xlsm
But I need to open the file in location B eg. C:\User\Testing\B\client_01.xlsm where the location saved the related documents in there.
sometimes open in location C \ D etc.
So the path link save in macro needs to be variant as the location changes
Please advice as I'm beginner in VBA
Thanks
Sub Testing
Dim FilePath As String
Dim FileName As String
Dim wb As Workbook
Set wb = ThisWorkbook
FileName = wb
FilePath = "C:\User\Testing\",FileName,"\client_01".xlsm"
End Sub
FileName is a string so you'll have to use wb.Name
As for the FilePath, you can't concatenate like that, use & instead
FilePath = "C:\User\Testing\" & FileName & "\client_01.xlsm"
That is ofc if the workbook your code is in is called "A", "B", "C" or whatever you wanted.
If you want to use the path of the workbook that you're code is in: use something like:
Sub Testing
Dim FilePath As String
Dim FileName As String
Dim wb As Workbook
Set wb = ThisWorkbook
FileName = wb.Name
FilePath = ThisWorkbook.Path & "\" & FileName & "\client_01".xlsm"
End Sub
You can adjust as you see fit ofc
To return the current workbook's folder path as a string, use:
FilePath = wb.Path
Then if your code opens to related documents (lets say their names are saved as string variables relateddoc1 etc):
Workbooks.Open(FilePath & "\" & relateddoc1)

Save as txt with name and file location based on cell value

i need to export as txt some sheets , i can't do it . I try it in that way but don't go to the right file location :
Dim filePath As String
Dim fileName As String
filePath = Sheet1.Range("B3").Value
fileName = Sheet22.Range("N3").Value
Sheet14.Select
ActiveWorkbook.SaveAs fileName:= _
fileName,
FileFormat:= _
xlText, CreateBackup:=False
it's that correct ?
Unless you want to rename your current worksheets all the time you save them you should try this:
Dim ws As Excel.Worksheet
Dim fileName As String
Sub Export_WS()
Set ws = Worksheets("Exportsheet")
'Get file path your way by this Sub
GetFile
'Copy the ws to a new workbook
ws.Copy
'With the new wb:
With Workbooks(Workbooks.Count)
'Save and close the new workbook
.SaveAs fileName:=fileName, FileFormat:=xlTextPrinter
.Close False
End With
End Sub
Here is how I got the file link
Function GetFile() As String
Dim filename_path As Variant
filename_path = Application.GetOpenFilename(FileFilter:="xyz* (*.txt), *.txt", Title:="Select file")
If filename_path = False Then Exit Function
GetFile = filename_path
fileName = filename_path
End Function
Hope that helps.
Or like you suggested by a Cell Value
fileName = SheetXYZ.Range("A1").Value
Of course you can also assign the filename manually:
fileName = "c:filename.txt"
Additional Information is here:
File Operations

Combining macros in Excel

I'm trying to combine/nest 3 different functions in Excel VBE: open, loop, and click. I have them written out separately, but am unsure of how to combine them. I've tried the "call macro" function but got a compile error returned to me.
The goal is to open a bunch of files within a certain folder and click on the URL in all of them (the URL will not always be the same, so I need a click function that targets any unknown URL within a sheet).
Open macro:
Sub openMyfile()
Dim Source As String
Dim StrFile As String
Source = "/users/kmogilevsky/Desktop/IC_new/"
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Loop
End Sub
Loop macro:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Set MySource = MyObj.GetFolder("/users/kmogilevsky/Desktop/IC_new/")
For Each file In MySource.Files
If InStr(file.Name, "test") > 0 Then
End If
Next file
End Sub
Click macro (this needs some work):
Private Sub CommandButton1_Click()
Call NewSub
End Sub
Sub ReadWorkbooksInCurrentFolder()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim MyPath As String
Dim strFilename As String
'Stop annoying popups while macro is running
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
'When working with many open workbooks its good to explicitly reference all workbooks, makes sure your code works and easier to read, understand and remember which workbook is which.
Set wbDst = ThisWorkbook
srcSheetName = "Data"
dstSheetName = "Results"
'I want to loop through all .xlsx files in the folder
MyPath = ThisWorkbook.Path
strFilename = Dir(MyPath & "\*.xlsx", vbNormal)
If Len(strFilename) = 0 Then
MsgBox "No workbooks found ending in .xlsx in current folder"
Exit Sub
End If
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
Call CollectData(wbDst, wbSrc, dstSheetName, srcSheetName)
wbSrc.Close
strFilename = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub CollectData(ByRef wbDst as Workbook, ByRef wbSrc as Workbook, dstSheetName as String, srcSheetName as String)
'Copy cell A1 contents in source workbook to destination workbook cell A1
wbDst.Sheets(dstSheetName).Range("A1") = wbSrc.Sheets(srcSheetName).Range("A1")
End Sub
Please edit the subroutine CollectData() so that it suits your needs, i.e. performs the click / url open. (I am not familiar with opening urls from excel, but I loop through workbooks often)
This code will open all Excel files in the IC_New folder on the desktop.
It will then look at each sheet and follow any hyperlinks that are on the sheet.
Sub Open_ClickHyperlinks()
Dim sPath As String
Dim vFiles As Variant
Dim vFile As Variant
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
Dim HLink As Hyperlink
sPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & Application.PathSeparator & _
"IC_New" & Application.PathSeparator
'Return all files that have an extension starting with xls.
vFiles = EnumerateFiles(sPath, "xls*")
'Loop through each file.
For Each vFile In vFiles
'Open the file
Set wrkBk = Workbooks.Open(Filename:=vFile, UpdateLinks:=False)
With wrkBk
'Loop through each worksheet in the file.
For Each wrkSht In .Worksheets
'Loop through each hyperlink on the worksheet.
For Each HLink In wrkSht.Hyperlinks
HLink.Follow
Next HLink
Next wrkSht
.Close SaveChanges:=False
End With
Next vFile
End Sub
'Get all files in the specified folder, default to include all subfolders as well.
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function

Filename is empty when trying to open file

I try to merge workbooks from a folder in a new workbooks. The VBA code reads the excel file from folder, add every file name to a list box and then, after pressing the button "Start", add very file to the workbook. That is the idea.
The code is as folows:
When opening the file the userform is shown:
Private Sub Workbook_Open()
UserForm1.Show
End Sub
When activating userform, the list box is populated:
Private Sub UserForm_Activate()
Const strFolder As String = "C:\Users\user\Desktop\tmp\"
Const strPattern As String = "*.xls"
Dim strFile As String
Dim collection As New collection
Dim i As Integer
Dim isMerger As Integer
Dim lngth As Integer
strFile = Dir(strFolder & strPattern, vbNormal)
If (StrComp(strFile, "FileMerger.xls") <> 0) Then
If (Len(strFile) <> 0) Then
col.Add (strFolder & strFile)
Do While Len(strFile) > 0
strFile = Dir
If (StrComp(strFile, "FileMerger.xls") <> 0) Then
If (Len(strFile) <> 0) Then
col.Add (strFolder & strFile)
End If
End If
Loop
End If
End If
Vars.xlsFiles = ColToArray(collection)
For i = 1 To UBound(Vars.xlsFiles)
lstFiles.AddItem (Vars.xlsFiles(i))
Next i
End Sub
At this moment listbox and array Vars.xlsFiles are populated; they are OK.
Click on Start button in the userform:
Private Sub cmdStart_Click()
Dim fileName As String
Dim sheet As Worksheet
Dim i As Integer
Dim ub As Integer
ub = UBound(Vars.xlsFiles)
For i = 1 To ub
Workbooks.Open fileName:=Vars.xlsFiles(i), ReadOnly:=True
For Each sheet In ActiveWorkbook.Sheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(fileName).Close
Next i
End Sub
In the folder are 3 files. Their name are in the listbox. But when the first is to be closed I received an error message and after debugging it says that fileName ="" (line Workbooks(fileName).Close).
whatever I try I got the same error, i.e. fileName = "".
What to do ?
Your never set the variable fileName, so it's still the default value "". Maybe you got confused by the fileName:=Vars.xlsFiles(i) of the Workbooks.Open method. That just sets the option FileName of that method. Use some unique name to avoid confusion and set it to Vars.xlsFiles(i) or use
Workbooks(Vars.xlsFiles(i)).close
FileName:= is a named parameter of the Workbooks.Open method. It does not set the value of the cmdStart_Click's fileName variable.
Private Sub cmdStart_Click()
Dim fileName As String
Dim sheet As Worksheet
Dim i As Integer
Dim ub As Integer
ub = UBound(Vars.xlsFiles)
For i = 1 To ub
fileName = Vars.xlsFiles(i)
Workbooks.Open FileName:=fileName, ReadOnly:=True
For Each sheet In ActiveWorkbook.Sheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(fileName).Close
Next i
End Sub

Closing Macro with current date

I am using a macro to close several files and one of them uses a current date in the file name. I need the macro to click in the workbook and then close it and save it. I think I almost have it but I just can'tget the macro to click in the active workbook, which filename will change daily. This is what I have.
Dim ClosePath As String
Dim ClosePathDate As String
ClosePath = "File_":
ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"
Windows("ClosePathDate").Activate
Sheets("Sheet1").Select
Range("A1").Select
ActiveWorkbook.Close SaveChanges:=True
I am not sure how to use " Windows("ClosePathDate") " I also tried Windows=ClosePathDate.Activate, no luck.
Please help.
This will work even if the workbook is open in another Excel Instance. BTW, you do not need to select it in order to close it.
Sub Sample()
Dim ClosePath As String
Dim ClosePathDate As String
Dim xlObj As Object
ClosePath = "File_":
ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"
'~~> Replace "C:\" with the relevant path
Set xlObj = GetObject("C:\" & ClosePathDate)
xlObj.Application.Workbooks(ClosePathDate).Close SaveChanges:=False
End Sub
Another way
Sub Sample()
Dim wb As Workbook
Dim ClosePath As String
Dim ClosePathDate As String
ClosePath = "File_":
ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"
Set wb = Workbooks(ClosePathDate)
wb.Close SaveChanges:=False
End Sub