当使用宏将数据文件导入新选项卡时,如何提示用户选择文件?[英] How do I prompt the user to select the file, when using macro to import a data file into a new tab?

问题描述

我有一个宏,该宏目前正在创建一个新的表格,并将另一个Excel文件导入此新表.

该表中的数据比将工作簿的其他领域拉入.

正在导入的文件将不断具有不同的文件名.如何调整以下代码以提示用户选择文件? (目录不会更改).

sub ImportDemand() sheets.add

Sheets(2).Select
Sheets(2).Name = "ImportedDemand"
Range("E42").Select
With ActiveSheet.QueryTables.Add(Connection:=Array( _
    "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=\\Folder\ImportFile_2011.04.05.xls;Mode=Share Deny Write;Extended Properties=""HDR=YES;"";Jet OLEDB:System d" _
    , _
    "atabase="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=35;Jet OLEDB:Database Locking Mode=0;" _
    , _
    "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create Sys" _
    , _
    "tem Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Repli" _
    , "ca Repair=False;Jet OLEDB:SFP=False"), Destination:=Range("A1"))
    .CommandType = xlCmdTable
    .CommandText = Array("_All_Demand$")
    .Name = "ImportFile_2011.04.05"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .SourceDataFile = _
    "\\Folder\ImportFile_2011.04.05.xls"
    .Refresh BackgroundQuery:=False
End With

结束子

推荐答案

您可以使用GetOpenFilename:

.SourceDataFile = Application.GetOpenFilename("Excel workbooks (*.xls), *.xls")

另一个选项是filedialog对象.它提供了更大的灵活性.

Dim fdgOpen As FileDialog
Set fdgOpen = Application.FileDialog(msoFileDialogOpen)
fdgOpen.Title = "Please open a data file..."
fdgOpen.InitialFileName = "C:\MyDocuments\MyDir\"
'Other settings...
fdgOpen.Show
.SourceDataFile = fdgOpen.SelectedItems(1)

本文地址:https://www.itbaoku.cn/post/740256.html