所以我使用CSV文件,我需要打开excel转到数据 - >从文本和格式某些列的某些方式。 我录制了一个宏,但它总是打开录制宏时使用的文件。 如何修改宏以打开对话框让我每次都选择一个文件? 我在互联网上找到了这段代码,但我不知道如何将它与我在VBA中记录的宏集成。
Dim MyFile As String
MyFile = Application.GetOpenFilename()
现在我在下面的宏中使用"记录宏"按钮在excel中创建的代码如何以及在哪里以及替换?
Sub random_name()
'
' random_name Macro
'
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;MyFile = Application.GetOpenFilename()" _
, Destination:=Range("$A$1"))
.Name = "filename"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
谢谢!
答案 0 :(得分:1)
嘿我修改了你的代码:
Sub random_name()
'
' random_name Macro
'
'
Dim connectioString As String
connectioString = "TEXT;" & ListFile
With ActiveSheet.QueryTables.Add(Connection:= _
connectioString _
, Destination:=Range("$A$1"))
.Name = "filename"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
beneth粘贴此功能:
Function ListFile()
' ----- Creating a dialog object -----------------------------------
Dim oDiag As FileDialog
Dim vrtSelectedItem As Variant
Dim i As Integer
Set oDiag = Application.FileDialog(msoFileDialogFilePicker)
i = 0
With oDiag
' ----- Going thru all of the files --------------------------------
.AllowMultiSelect = False
If .Show = -1 Then
ListFile = .SelectedItems(1)
End If
End With
Set oDiag = Nothing
End Function
我现在不是100%肯定如果filedialog需要参考告诉我它是否有效:)
答案 1 :(得分:0)
试试这个:
Path = Application.GetOpenFilename()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Path, Destination:=Range("$A$1"))