简体   繁体   English

VBA使用文件对话框进行搜索,然后复制并粘贴

[英]VBA use filedialog to search, then copy and paste

Right now my code copies & pastes all of the data without any specific selection criteria. 现在,我的代码将复制并粘贴所有数据,而没有任何特定的选择条件。 I'm trying to copy and paste specific information from certain files based upon their name into the active worksheet. 我正在尝试根据文件的名称将某些文件中的特定信息复制并粘贴到活动工作表中。 I believe there is some function that I need that can help me with this. 我相信我需要一些功能可以帮助我解决这个问题。 Any help would be great. 任何帮助都会很棒。 Thanks. 谢谢。

Private Sub CommandButton1_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set wbb = ThisWorkbook
Set sh = wbb.Worksheets("Sheet1")

With fd
    .Title = "Please select Job Folder"
    .AllowMultiSelect = True
    Err.Clear
    FileChosen = fd.Show
    If MsgBox("Files selected, continue?", vbYesNo) = vbNo Then Exit Sub

    For i = 1 To fd.SelectedItems.Count
        file = fd.SelectedItems(i)
        Workbooks.Open Filename:=file, ReadOnly:=True
        If file = "" Then Exit Sub
        filesheet = "Sheet1"
        ActiveWorkbook.Sheets(filesheet).Range("A1:A3").Copy
        LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row
        sh.Cells(sh.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        ActiveWorkbook.Close savechanges:=False
    Next i
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

伪码

But you already have the answer on the posted sheet! 但是您已经在已发布的表格上找到了答案!

To check for a string within another string, use the InStr() function: 要检查另一个字符串中的一个字符串,请使用InStr()函数:

If InStr(CStr(file), "PartOfFileName") <> 0 Then
  'file found, copy specific parts to that file
End If

Here are some more good examples on how to use the function. 这里有一些关于如何使用该功能的更好的例子。

It is advised to 'Dim' all your variables to have better control over your code. 建议对所有变量进行“模糊处理”,以更好地控制代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM