excel - 用于从多个 csv 中选择特定列并导入到一个工作表的宏
问题描述
我在一个目录中有多个 CSV,我需要选择特定文件而不是整个目录,并且我希望能够选择我想要的列 (X) 并将其导入到单个工作表中!
我已经编写了上面的代码,但我正在努力添加一个输入框,该输入框可以选择我想从每个 CSV 中提取的列。此外,每当我导入 CSV 时,都没有正确排序。我发现我需要应用这个公式""=LEFT(F1;1)&TEXT(SUBSTITUTE(F1;LEFT(F1;1);"";"00") " "
,但不知道如何在代码中应用以重命名 .csv 文件。
Sub ImportCSVsWithReferenceI()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
Dim Newname As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet.Add
Newname = InputBox("Name for new worksheet?")
If Newname <> "" Then
Sheets.Add Type:=xlWorksheet
ActiveSheet.Name = Newname
End If
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then
xSht.UsedRange.Clear
xCount = 1
Else
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
End If
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Rows(1).Insert xlShiftDown
Range("A1") = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Cells(1, xCount)
xWb.Close False
xFile = Dir
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "error"
End Sub
数据示例(有时我想提取列 A 或 B 或 C 或 ....:
结果示例:
解决方案
推荐阅读
- php - 通过 JSON 数字索引标准类对象创建 foreach 循环
- android - Android Studio:静态手机预览
- arrays - 汇编语言中的多维数组 (2x2) 初始化 - Y86
- python - 如何为 Google Cloud Function 提供适当的身份验证以在 Python 中访问日历 API
- unity3d - 将游戏对象从 Unity 中的生成器连接到窗格?
- javascript - 如何在不刷新页面的情况下自动更新角度购物车中的产品数量
- vue.js - vue v-else 没有对应的 v-if
- javascript - Vue-Router 仅适用于某些路由
- android - 如何从 MainActivity 传递 arraylist 以将 listview 显示到 Main2Activity?
- parallel-processing - 如何使用 Rayon 检测整数总和的溢出?