Using File Opened via File Dialog with VBA - excel

I am trying to Copy information from a tab in file opened via File Dialog and paste it into "ThisWorkbook"
Below is my attempt. I keep getting the error
"object doesn't support this property or method"
on the line in bold font.
Sub UpdateWeeklyJobPrep()
Dim xlFileName As String
Dim fd As Office.FileDialog
Dim source As Workbook
Dim currentwk As Integer
Dim wksheet As String
Dim target As ThisWorkbook
Dim fso As Object
Dim sourcename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Calc the current fiscal week
currentwk = WorksheetFunction.WeekNum(Now, vbMonday)
wksheet = "FW" & currentwk
With fd
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
If .Show Then
xlFileName = .SelectedItems(1)
Else
Exit Sub
End If
End With
'Opens workbook
Workbooks.Open (xlFileName), ReadOnly:=True
'Get file name from path
Set fso = CreateObject("Scripting.FileSystemObject")
sourcename = fso.GetFileName(xlFileName)
sourcename = Left(sourcename, InStrRev(sourcename, ".") - 1)
'Copy/Paste Code Here
**Workbooks(sourcename).Activate**
Workbooks(sourcename).Worksheets(wksheet).Column("F").Copy
target.Activate
target.Sheets("Data Source").Column("C").PasteSpecial
'close workbook with saving changes
source.Close SaveChanges:=False
Set source = Nothing
End Sub

I think I have a solution. Primarily, as mentioned above in my comment, you should use a variable to hold your new, open workbook.
Sub UpdateWeeklyJobPrep()
Dim xlFileName As String
Dim fd As Office.FileDialog
Dim source As Workbook
Dim currentwk As Integer
Dim wksheet As String
Dim fso As Object
Dim sourcename As String
Dim mainWB As Workbook
Set mainWB = ThisWorkbook
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Calc the current fiscal week
currentwk = WorksheetFunction.WeekNum(Now, vbMonday)
wksheet = "FW" & currentwk
With fd
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
If .Show Then
xlFileName = .SelectedItems(1)
Else
Exit Sub
End If
End With
'Opens workbook
Dim newWB As Workbook
Set newWB = Workbooks.Open(xlFileName, ReadOnly:=True)
'Copy/Paste Code Here
mainWB.Sheets("Data Source").Column("C").Values = newWB.Worksheets(wksheet).Column("F").Values
newWB.Close savechanges:=False
Set newWB = Nothing
End Sub
I also changed the Copy/PasteSpecial bit, assuming you just needed values. Note since you're copying a whole column this might take time. You'd probably instead want to minimize that range to the used rows only, but I'll leave that as an exercise for the reader.

Related

What is the error in my code that list all the tabs in a file?

I want my code to pick up a file (file 2) and then list out all the tabs in that file in my current spreadsheet ("Input_tab" from file1). The code is not making creating the list. What is the error in my code?
Sub ListSheets()
Dim FilePicker As FileDialog
Dim mypath As String
Dim sheet_count As Integer
Dim i As Integer
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(Sheet1)
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)
With FilePicker
.Title = "Please Select a File"
.ButtonName = "Confirm"
.AllowMultiSelect = False
If .Show = -1 Then
mypath = .SelectedItems(1)
Else
End
End If
End With
Workbooks.Open Filename:=mypath
sheet_count = Sheets.Count
For i = 1 To sheet_count
ws.Cells(i, 1) = Sheets(i).Name
Next i
ActiveWorkbook.Close savechanges:=False
End Sub
When working with multiple workbooks (or really all the time) you should always be explicit about what (eg) Sheets collection you want to refer to (ie. in which workbook?)
This works for me
Sub ListSheets()
Dim mypath As String
Dim i As Long 'prefer Long over Integer
Dim ws As Worksheet, wb As Workbook
Set ws = ThisWorkbook.Sheets("Sheet1")
mypath = GetFilePath("Please Select a File", "Confirm")
If Len(mypath) = 0 Then Exit Sub
Application.ScreenUpdating = False 'hide opening workbook
Set wb = Workbooks.Open(Filename:=mypath, ReadOnly:=True) 'get a reference to the opened workbook
ws.Cells(1, 1).value = mypath '<<<
For i = 1 To wb.Sheets.Count
ws.Cells(i + 1, 1) = wb.Sheets(i).Name
Next i
wb.Close savechanges:=False
End Sub
'return user-selected file path
Function GetFilePath(TitleText As String, ButtonText As String) As String
With Application.FileDialog(msoFileDialogFilePicker)
.Title = TitleText
.ButtonName = ButtonText
.AllowMultiSelect = False
If .Show = -1 Then GetFilePath = .SelectedItems(1)
End With
End Function

VBa code open closed file and copy columns working but nothing doing

I have a code which should open input file and copy from there some specific columns. This macro not showing any bug its working but nothing happend, i dont see any action. I have Excel 2016
Sub btnExport_Click()
Dim strPath As String
Dim wbMe, wb As Workbook
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = ActiveWorkbook
Set wb = Workbooks.Open(strPath, False, True)
wb.Sheets(1).Columns("A:C").Copy Destination:=wbMe.Sheets(1).Range("A1")
wb.Sheets(1).Columns("H").Copy Destination:=wbMe.Sheets(1).Range("D1")
wb.Close False
Set wb = Nothing
Beep
MsgBox "The data was imported"
End Sub
Private Function selectFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(3)
With fd
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
.Title = "Please select file to import."
.Filters.Clear
.Filters.Add "Excel", "*.xlsm"
If Show = True Then selectFile = .SelectedItems(1)
End With
End Function
This is in your worksheet module:
Option Explicit
Sub btnExport_Click()
Dim strPath As String
Dim wbMe As Workbook, wb As Workbook
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = ActiveWorkbook
Set wb = Workbooks.Open(strPath, False, True)
copyRangeValues wb.Sheets(1).Columns("A:C"), wbMe.Sheets(1).Range("A1")
copyRangeValues wb.Sheets(1).Columns("H"), wbMe.Sheets(1).Range("D1")
wb.Close False
Set wb = Nothing
Beep
MsgBox "The data was imported"
End Sub
Add a module to your project if you haven't yet.
Paste the following functions to that module
Option explicit
Public Function selectFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(3)
With fd
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
.Title = "Please select file to import."
.Filters.Clear
.Filters.Add "Excel", "*.xlsm"
If Show = True Then selectFile = .SelectedItems(1)
End With
End Function
Public Sub copyRangeValues(rgSource As Range, rgTargetCell As Range)
'generic routine to copy one range to another
'rgTargetCell = top left corner of target range
Dim rgTarget As Range
'resize rgTarget according to dimensions of rgSource
With rgSource
Set rgTarget = rgTargetCell.Resize(.Rows.Count, .Columns.Count)
End With
'write values from rgSource to rgTarget - no copy/paste necessary!!!
'formats are not copied - only values
rgTarget.value = rgSource.value
End Sub

How can I open multiple files to copy data into a master workbook in new tab?

I have a master Excel file that needs to inherit data from .csv files.
When I run the VBA, it will pop up the file explorer, let me select multiple files and loop over them and create new sheets.
When I try to copy the data into the sheet that it created, it gives me a type mismatch error.
Sub OpenLMSFiles()
Dim fd As FileDialog
Dim FileChosen As Integer
Dim FileName As String
Dim tempWB As Workbook
Dim i As Integer
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = "Libraries\Documents"
fd.InitialView = msoFileDialogViewList
fd.AllowMultiSelect = True
FileChosen = fd.Show
If FileChosen = -1 Then
For i = 1 To fd.SelectedItems.Count
Set tempWB = Workbooks.Open(fd.SelectedItems(i))
Call ReadDataFromSourceFile(tempWB)
Next i
End If
End Sub
Private Sub ReadDataFromSourceFile(src As Workbook)
Application.ScreenUpdating = False
ThisWorkbook.Sheets.Add
Workbooks(src).Worksheets(src.ActiveSheet).Range("A1:Z500").Copy _
Workbooks(ThisWorkbook).Worksheets(ThisWorkbook.ActiveSheet).Range("A1:Z500")
End Sub
The cause of the error is the way you are referencing workbooks and worksheets, which are collections that take index arguments (integer or string). For example you can reference a workbook as Workbooks(1) (bad idea) or Workbooks("FileName.xlsx") (better). Similarly use Sheets(1) or Sheets("SheetName").
src is a Workbook -> simply use src.Sheets(). Because csv files have only 1 worksheet it is safe to use src.Worksheets(1) (Sheets and Worksheets are equivalent).
Anyway, here is a working code. I rearranged the code as I think ReadDataFromSourceFile should encapsulate opening and closing the csv file as well as reading data from it (only an opinion)
Sub ImportLMSFiles()
Dim fd As FileDialog
Dim FileChosen As Long
Dim FileName As String
Dim i As Long
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = "Libraries\Documents"
fd.InitialView = msoFileDialogViewList
fd.AllowMultiSelect = True
FileChosen = fd.Show
If FileChosen = -1 Then
For i = 1 To fd.SelectedItems.Count
Call ReadDataFromSourceFile(fd.SelectedItems(i))
Next i
End If
End Sub
Private Sub ReadDataFromSourceFile(sSrcFilename As String)
' Validate the name
If Right(sSrcFilename, 4) <> ".csv" Then Exit Sub
Application.ScreenUpdating = False
Dim shtDest As Worksheet: Set shtDest = ThisWorkbook.Sheets.Add
Dim wbSrc As Workbook: Set wbSrc = Workbooks.Open(sSrcFilename)
' csv files have only 1 sheet
' UsedRange is exactly what it sounds like
With wbSrc.Sheets(1)
.UsedRange.Copy shtDest.Range(.UsedRange.Address)
' if you want to rename the new sheet
' Bug: another sheet might have the same name -> u need check for that
' Here I'm just ducking it: name not changed
On Error Resume Next
shtDest.Name = .Name
On Error GoTo 0
End With
wbSrc.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub

Copying data from one sheet to another with changing file name

I'm trying to take data from one workbook and paste it into another.
The workbooks change every month. I'd like to select the source file using Application.fileDialog.
Sub CopyTest ()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Store in fullpath variable
fullpath = .SelectedItems.Item(1)
End With
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Dim sourceSheet As Worksheet
Set sourceSheet = sourceBook.Worksheets("Account Detail GHOA ")
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(“Macro Data”)
sourceSheet.Range("A1:W79").Copy targetSheet.Range("A1:W79")
End Sub
I referenced this question to find the above partial solution: Excel VBA file name changes
I found the solution thank you all for the help!
Replace the sheet names with the ones for your work book. This code will enable you to select the source file (where data is being pulled from) and the target file (where you'd like it to paste to). This worked great for what I needed.
I plan on taking the raw data that I imported in (which changes on a monthly basis) and using vlookups to populate the summary tab.
Sub CopyTest()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Store in sourceBook variable
sourceBookPath = .SelectedItems.Item(1)
End With
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Dim sourceSheet As Worksheet
Set sourceSheet = sourceBook.Worksheets("Account Detail GHOA")
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Store in targetBook variable
targetBookPath = .SelectedItems.Item(1)
End With
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
With Worksheets("Macro Data").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Macro Data"
Application.DisplayAlerts = True
End With
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets("Macro Data")
sourceSheet.Range("A4:W79").Copy targetSheet.Range("A1:W79")
End Sub

GetOpenFilename opens Dialogue box behind PowerPoint Presentation

I'm using VBA in powerPoint to update links to Excel Objects in my PowerPoint and everything is working well. The only Issue I have is that sometimes the Select File dialogue box opens behind the active Powerpoint and the only way to select it is to CTRL+ALT+Del and select the Excel File Chooser and set it as active. Is there a way to make it always be the active dialogue box when it opens? Here's the code I'm using:
Sub UpdateLinks()
Dim sld As Slide
Dim sh As Shape
Dim strNms As String
Dim intI As Integer
Dim strNewPath
Dim ExcelFile
Dim exl As Object
Set exl = CreateObject("Excel.Application")
'Set exl = exl.ActiveWindow
'exl.Active = True
'Open a dialog box to promt for the new source file.
ExcelFile = exl.Application.GetOpenFilename(, , "Select Excel File")
'Go through every slide
For Each sld In ActivePresentation.Slides
For Each sh In sld.Shapes
If sh.Type = msoLinkedOLEObject Then
With sh.LinkFormat
strNms = .SourceFullName
intI = InStr(1, strNms, "!")
strNewPath = ExcelFile & Mid(strNms, intI, Len(strNms) - intI + 1)
.SourceFullName = strNewPath
End With
End If
Next sh
Next sld
ActivePresentation.UpdateLinks
End Sub
Thanks.
Suggestion: try this version of a file picker instead:
Sub FileDialogExample()
' Courtesy of John Wilson
' www.pptalchemy.co.uk
Dim fd As FileDialog
Dim sFilename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Filters.Add "Excel Files", "*.xls, *.xlsx"
.InitialFileName = Environ("USERPROFILE") & "\Desktop\"
.AllowMultiSelect = False
If .Show = True Then sFilename = .SelectedItems(1)
End With
'do whatever with sFilename
MsgBox "You picked " & sFilename
End Sub

Resources