|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 kwinawyeth 于 2024-3-26 14:26 编辑
简单写了几段程序,可以简单达到要求。点击【导入】按钮就可以了
- Sub InputData()
- On Error Resume Next
- Dim fl, fileType As String, data
-
- '弹出文件选择对话框
- ChDrive Left(ThisWorkbook.FullName, 1) '指向当前盘
- ChDir ThisWorkbook.Path '指向当前路径
- fl = Application.GetOpenFilename("文本文件,*.xls;*.xlsx", 1, "请点击需要导入的文件")
- If fl = False Then Exit Sub
-
- Dim dateStr As String, iCount As Long
-
- Application.ScreenUpdating = False
-
- dateStr = ExtractDate(fl) '提取日期
-
- '打开excel文件,获取数据
- data = GetXlsData(fl)
- iCount = UBound(data, 2)
-
-
- '保存数据
- Call InputSheet(data, dateStr) '写入表格中
-
- Application.ScreenUpdating = True
-
- Application.StatusBar = "数据已经导入,共导入数据" & iCount & "条"
-
- End Sub
- Private Function GetXlsData(fl) '从excel文件中提取文件
-
- Dim mySheet, ileName As String
- Workbooks.Open fl
- fileName = Split(fl, "")(UBound(Split(fl, ""))) '获得选取文件的文件类型
- Set mySheet = Workbooks(fileName).Sheets(1)
-
- '文件已经打开,提取数据
- Dim endRow As Long
- Dim i As Long, j As Integer
- Dim result(), r As Long
-
- endRow = mySheet.Cells(mySheet.Rows.Count, 2).End(xlUp).Row
- r = 0
- For i = 3 To endRow '循环行
- If Cells(i, 2) <> "" Then
- r = r + 1
- ReDim Preserve result(1 To 8, 1 To r)
- For j = 2 To 9 '选号列
- result(j - 1, r) = mySheet.Cells(i, j) '注意split得到的数组是从0开始的
- Next j
- End If
- Next i
- Workbooks(fileName).Close SaveChanges:=False
- GetXlsData = result
-
- End Function
- Private Sub InputSheet(data, dateStr As String) '将数据写入到表格中
- Dim i As Long, j As Integer
- Dim sRow As Long, quan As String
-
- sRow = Cells(Rows.Count, 3).End(xlUp).Row
- For i = 1 To UBound(data, 2)
-
- sRow = sRow + 1
- quan = data(UBound(data), i)
- Cells(sRow, 1) = ExtractZhanDian(quan)
- Cells(sRow, 2) = dateStr
- For j = 1 To UBound(data)
- Cells(sRow, 2 + j) = data(j, i)
- Next j
- Next i
- End Sub
- Private Function ExtractDate(fl) As String '从文件名中提取日期
- Dim strArr, str As String
-
- strArr = Split(fl, ".")
- str = strArr(UBound(strArr) - 1)
-
- strArr = Split(str, "_")
- str = strArr(UBound(strArr))
- ExtractDate = Format(str, "0000-00-00")
-
- End Function
- Private Function ExtractZhanDian(quan As String) As String '从 所在组织全路径 中提取运维站点
- '中国南方电网有限责任公司/云南电网有限责任公司/昆明供电局/变电运行一所/500kV七甸巡维中心
- Dim strArr, str As String
-
- strArr = Split(quan, "/")
- str = strArr(UBound(strArr))
-
- strArr = Split(str, "V")
- str = strArr(UBound(strArr))
-
- str = Replace(str, "巡维中心", "") '去掉 运维中心
- str = Replace(str, "变电站", "") '去掉 变电站
- ExtractZhanDian = str
-
- End Function
复制代码
|
|