|
本帖最后由 盼哥 于 2023-4-8 19:58 编辑
- Option Explicit
- Option Base 1 '设置数组索引从1开始
- '专业VBA开发,生产优质代码!
- Sub test()
- Dim 规则1, 规则2, 位置1, 位置2
-
- '规则
- 规则1 = Array("餐点", "米面油其他", "调料副食")
- 规则2 = Array("蔬菜水果")
-
- 位置1 = "2023-3-1"
- 位置2 = "2023-3-6"
-
- Dim tmpWorkbook As Workbook
- ThisWorkbook.Sheets("采购单").Copy
-
- Set tmpWorkbook = ActiveWorkbook
-
- With tmpWorkbook.Sheets("采购单")
- Dim cell As Range
- Dim mergedCellRange As Range
- Dim i As Integer
-
- For Each cell In ActiveSheet.UsedRange
-
- If cell.MergeCells Then
- Set mergedCellRange = cell.MergeArea
- With mergedCellRange
- '获取合并单元格的内容
- Dim cellText As String
- cellText = cell.Value
-
- '取消合并单元格
- mergedCellRange.UnMerge
- cell.Value = cellText
-
- '将单元格内容填充到所有拆分出的单元格中
- For i = 1 To .Cells.Count
- .Cells(i).Value = cellText
- Next
- End With
- End If
- Next
- Dim arr
- arr = .UsedRange
-
- End With
- tmpWorkbook.Close False
- Dim s$
-
-
- For i = 1 To UBound(arr)
- s = arr(i, 1)
- If 条件成立(s, 规则1) Then
- Call 写入(i, arr, 位置1)
- Else
- If 条件成立(s, 规则2) Then
- Call 写入(i, arr, 位置2)
- End If
- End If
- Next
-
- End Sub
- Sub 写入(i, arr, 位置)
- Dim tRange As Range, r&
- On Error Resume Next
-
-
- With ThisWorkbook.Sheets("出库单")
- Set tRange = .UsedRange.Columns("C").Find(位置)
- If tRange Is Nothing Then
- Exit Sub
- End If
- r = tRange.Row
- .Rows(r).Insert Shift:=xlShiftDown
- .Cells(r, "D") = arr(i, 2)
- .Cells(r, "E") = arr(i, 4)
- .Cells(r, "F") = arr(i, 5)
- .Cells(r, "G") = arr(i, 6)
- .Cells(r, "H") = arr(i, 3)
- .Cells(r, "I") = arr(i, 1)
- .Cells(r, "K") = "入库"
- End With
-
- On Error GoTo 0
- End Sub
- Function 条件成立(s$, arr)
- 条件成立 = False
- Dim i&
- For i = 1 To UBound(arr)
- If s = arr(i) Then
- 条件成立 = True
- Exit For
- End If
-
- Next
- End Function
- Sub mkOBJ(book As Workbook, x$)
-
- '根据字符串创建Book对象
-
- '判断文件已经打开
- Dim eachBook
- For Each eachBook In Workbooks
- If InStr(eachBook.Name, x) > 0 Then
- Set book = eachBook
- Exit Sub
- End If
- Next
-
- Dim fName$
-
- fName = Dir(ThisWorkbook.Path & "" & "*" & x & "*")
-
- If fName = "" Then
- MsgBox x & "不存在"
- End
- Else
-
- fName = ThisWorkbook.Path & "" & Left(x, InStrRev(x, "")) & fName
- Set book = Workbooks.Open(fName)
- End If
-
- End Sub
复制代码
|
|