VBS Save File From Link

自闭症网瘾萝莉.ら 提交于 2019-12-31 05:18:04

问题


I wonder whether someone can help me please.

I wanting to use this solution in a script I'm trying to put together, but I'm a little unsure about how to make a change which needs to be made.

You'll see in the solution that the file type which is opened is a Excel and indeed it's saved as such. But I the files I'd like to open and save are a mixture of .docx and .dat (Used by Dragon software) files.

Could someone possible tell me please is there a way by which I can amend the code so it opens and saves the files in file types other than Excel workbooks.

The reason behind this question because I'm currently using a script which creates a list of files in a Excel spreadsheet from a given folder. For each file that is retrieved there is a hyperlink, which I'd like to add fucntionality to which enables the user to copy the file and save it to a location of their choice.

To help this is the code which I use to create the list of files.

Public Sub ListFilesInFolder(SourceFolder As Scripting.folder, IncludeSubfolders As Boolean)
    Dim LastRow As Long
    Dim fName As String
    On Error Resume Next

    For Each FileItem In SourceFolder.Files
        ' display file properties
        Cells(iRow, 3).Formula = iRow - 12
        Cells(iRow, 4).Formula = FileItem.Name
        Cells(iRow, 5).Formula = FileItem.Path
        Cells(iRow, 6).Select
        Selection.Hyperlinks.Add Anchor:=Selection, Address:= _
        FileItem.Path, TextToDisplay:="Click Here to Open"
        iRow = iRow + 1 ' next row number

        With ActiveSheet
        LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
        LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End With

For Each Cell In Range("C13:F" & LastRow) ''change range accordingly
    If Cell.Row Mod 2 = 1 Then ''highlights row 2,4,6 etc|= 0 highlights 1,3,5
        Cell.Interior.Color = RGB(232, 232, 232) ''color to preference
    Else
        Cell.Interior.Color = RGB(141, 180, 226) 'color to preference or remove
    End If
Next Cell

    Next FileItem


    If IncludeSubfolders Then
        For Each SubFolder In SourceFolder.SubFolders
            ListFilesInFolder SubFolder, True
        Next SubFolder
    End If
    Set FileItem = Nothing
    Set SourceFolder = Nothing
    Set FSO = Nothing
End Sub

Many thanks and kind regards

Chris


回答1:


Miguel provided a fantastic solution which on initial testing appeared to work 100%. But as you will see from the comments at the end of the post there were some issues when the user cancelled the operation, so I made another post at this link where the problems were ironed out. Many thanks and kind regards. Chris




回答2:


The code below shows how to retrieve the extension of a file, define an array with “allowed” extensions, and match the extension of the file to the array.

This is the outline for file manipulation, you'll just need to tailor it to you needs

Dim MinExtensionX
Dim Arr() As Variant
Dim lngLoc As Variant


'Retrieve extension of file

  MinExtensionX = Mid(MyFile.Name, InStrRev(MyFile.Name, ".") + 1)

  Arr = Array("xls", "xlsx", "docx", "dat") 'define which extensions you want to allow

On Error Resume Next

  lngLoc = Application.WorksheetFunction.Match(MinExtensionX, Arr(), 0)

If Not IsEmpty(lngLoc) Then '

  'check which kind of extension you are working with and create proper obj manipulation 
  If MinExtensionX = "docx" then

     Set wApp = CreateObject("Word.Application")
     wApp.DisplayAlerts = False
     Set wDoc = wApp.Documents.Open (Filename:="C:\Documents\SomeWordTemplate.docx", ReadOnly:=True)

     'DO STUFF if it's an authorized file. Then Save file.

     With wDoc

          .ActiveDocument.SaveAs Filename:="C:\Documents\NewWordDocumentFromTemplate.docx"

     End With

     wApp.DisplayAlerts = True

     End if
End If

For files .Dat its a bit more complex, specially if you need to open/process data from the file, but this might help you out.

Edit:

2: Comments added

Hi IRHM,

I think you want something like this: 'Worksheet_FollowHyperlink' is an on click event that occurs every time you click on an Hyperlink within a Worksheet, You can find more here

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

'disable events so the user doesn't see the codes selection
Application.EnableEvents = False

    Dim FSO
    Dim sFile As String
    Dim sDFolder As String
    Dim thiswb As Workbook ', wb As Workbook

    'Define workbooks so we don't lose scope while selecting sFile(thisworkbook = workbook were the code is located).
    Set thiswb = thisworkbook
    'Set wb = ActiveWorkbook ' This line was commented out because we no longer need to cope with 2 excel workbooks open at the same time.

    'Target.Range.Value is the selection of the Hyperlink Path. Due to the address of the Hyperlink being "" we just assign the value to a 
    'temporary variable which is not used so the Click on event is still triggers
    temp = Target.Range.Value
    'Activate the wb, and attribute the File.Path located 1 column left of the Hyperlink/ActiveCell
    thiswb.Activate
    sFile = Cells(ActiveCell.Row, ActiveCell.Column - 1).Value

    'Declare a variable as a FileDialog Object
    Dim fldr As FileDialog
    'Create a FileDialog object as a File Picker dialog box.
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)

    'Allow only single selection on Folders
    fldr.AllowMultiSelect = False
    'Show Folder picker dialog box to user and wait for user action
    fldr.Show

    'add the end slash of the path selected in the dialog box for the copy operation
    sDFolder = fldr.SelectedItems(1) & "\"

    'FSO System object to copy the file
    Set FSO = CreateObject("Scripting.FileSystemObject")
    ' Copy File from (source = sFile), destination , (Overwrite True = replace file with the same name)
    FSO.CopyFile (sFile), sDFolder, True

    ' check if there's multiple excel workbooks open and close workbook that is not needed
    ' section commented out because the Hyperlinks no longer Open the selected file
    ' If Not thiswb.Name = wb.Name Then
    '     wb.Close
    ' End If
Application.EnableEvents = True

End Sub

The above code Triggers when you click the Hyperlink and it promps a folder selection window.

You just need to paste the code into the Worksheet code. And you should be good to go.



来源:https://stackoverflow.com/questions/29691787/vbs-save-file-from-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!