|
楼主 |
发表于 2022-5-15 12:29
|
显示全部楼层
本帖最后由 丝竹乱 于 2022-5-15 13:53 编辑
2 公司内网的间的数据抓取
在公司内,生产工单、工艺清单、人员名单可能分属不同职能部门或人员维护。为确保所使用的资料是最新,往往耗费大量的时间和人力去处理。
在本工作簿中,尝试用另外一种方式来处理这种事情。
将局域网内的文件路径、文件名、表格名用工作表“【更新设置】”保存。使用者只需要修改相应的内容就行。
这段代码可略作修改就可以移植到其它工作簿中。
处理流程:
读取“【更新设置】” ==》打开指定路径工作簿==》读取相应的工作表,建立数组==》粘贴到本地工作簿。
(注意,读取数组的过程中,加入了删除源数据错误信息的步骤,这样可以减少程序报错)
Public Sub 联网更新()
'2021-02-19
Dim ExcelAPP As Object
Dim ExcelWB As Object
Dim FSO As Object
Dim aryList(), aryINFO(), aryTempSH, arySoSH
Dim FileSpec$, rj%, iSH%
Dim booErrFile As Boolean
Application.ScreenUpdating = False
Application.EnableEvents = False
With ThisWorkbook
.Unprotect Password:="1024"
End With
aryINFO = CreatingArrayFromRange(1, 1, "【更新设置】")
Set FSO = CreateObject("Scripting.FileSystemObject")
For rj = 2 To UBound(aryINFO)
aryINFO(rj, 8) = Empty
If aryINFO(rj, 1) = "数据更新" Then
If IsEmpty(aryINFO(rj, 2)) Then
FileSpec = ThisWorkbook.Path & "\" & aryINFO(rj, 3)
Else
FileSpec = aryINFO(rj, 2) & "\" & aryINFO(rj, 3)
End If
If FSO.FileExists(FileSpec) Then
If aryINFO(rj, 6) <> FSO.GetFile(FileSpec).DateLastModified Or aryINFO(rj, 8) <> "完成" Then
aryINFO(rj, 6) = FSO.GetFile(FileSpec).DateLastModified
Set ExcelWB = GetObject(FileSpec)
Set ExcelAPP = ExcelWB.Application '打开指定文件
aryTempSH = Split(aryINFO(rj, 5), "/")
arySoSH = Split(aryINFO(rj, 4), "/")
For iSH = LBound(aryTempSH) To UBound(aryTempSH)
If SheetIsExist(CStr(aryTempSH(iSH))) = False Then '本地工作表为假则新建
ThisWorkbook.Sheets.Add.Name = aryTempSH(iSH)
End If
If SheetIsExist(CStr(arySoSH(iSH)), ExcelWB.Name) Then '源工作表为假则报错
With ExcelWB.Worksheets(arySoSH(iSH))
aryList = CreatingArrayFromRange(1, 1, CStr(arySoSH(iSH)), , , ExcelWB.Name) '读取数据
With ThisWorkbook.Worksheets(aryTempSH(iSH)) '将数据贴入本地工作表
.Unprotect Password:="GaiShan"
.Cells.Clear
.[a1].Resize(UBound(aryList, 1), UBound(aryList, 2)) = aryList
.Cells.EntireColumn.AutoFit
.Cells.EntireRow.AutoFit
.Visible = False
End With
aryINFO(rj, 7) = Now
aryINFO(rj, 8) = "完成"
Erase aryList
End With
Else
aryINFO(rj, 8) = "源文件中工作表不存在或名称出错" & Chr(10) & aryINFO(rj, 8)
' MsgBox _
' "错误代码:" & Err.Number & Chr(10) & _
' "错误说明:" & Err.Description & Chr(10) & _
' "工作簿路径:" & FileSpec & Chr(10) & _
' "工作表名称:《" & arySoSH(iSH) & "》" & Chr(10) & "不存在或名称不符"
End If
Next iSH
ExcelWB.Close False '关闭工作簿
Set ExcelAPP = Nothing
End If
ElseIf aryINFO(rj, 1) = "数据更新" Then
aryINFO(rj, 8) = "源文件路径出错或文件不存在" & Chr(10) & aryINFO(rj, 8)
If Not booErrFile Then
MsgBox _
"错误代码:" & Err.Number & Chr(10) & _
"错误说明:" & Err.Description & Chr(10) & _
"工作簿路径:" & FileSpec & Chr(10) & _
"工作簿名称:《" & aryINFO(rj, 3) & "》" & Chr(10) & "不存在或名称不符" & _
Chr(10) & " 细节请查阅工作表“【更新设置】”。"
booErrFile = True
End If
End If
End If
Next rj
Set FSO = Nothing
With ThisWorkbook
.Worksheets("【更新设置】").Range("A1").Resize(UBound(aryINFO, 1), UBound(aryINFO, 2)) = aryINFO
.Save
End With
Application.EnableEvents = True
End Sub
|
|