gpt4 book ai didi

vba - Excel VBA 自动生成电子表格

转载 作者:行者123 更新时间:2023-12-02 11:40:57 37 4
gpt4 key购买 nike

我和我的 friend 目前有一个主电子表格,我需要定期将其分解为较小的电子表格。这曾经是一个手动过程,但我想将其自动化。我在 VBA 中创建了一个三步解决方案,它将帮助我完成以下任务:

  1. 对电子表格应用相关过滤器
  2. 将过滤后当前可见的数据导出到新电子表格
  3. 保存电子表格并返回 1(不同条件)

不幸的是,我很难实现它。每当我尝试生成电子表格时,我的文档就会挂起,开始执行多项计算,然后给出以下错误消息:

enter image description here

调试代码后,我在这一行收到一条错误消息:

enter image description here

一个 Excel 工作簿保持打开状态,只有一行可见(从包含标题信息的母版中提取的第二行),没有其他内容。

这里到底发生了什么?

这是我到目前为止的代码:

一切的核心

' This bit of code get's all the primary contacts in column F, it does 
' this by identifying all the unique values in column F (from F3 onwards)
Sub GetPrimaryContacts()
Dim Col As New Collection
Dim itm
Dim i As Long
Dim CellVell As Variant

'Get last row value
LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

'Loop between all column F to get unique values
For i = 3 To LastRow
CellVal = Sheets("Master").Range("F" & i).Value
On Error Resume Next
Col.Add CellVal, Chr(34) & CellVal & Chr(34)
On Error GoTo 0
Next i

' Once we have the unique values, apply the TOKEN NOT ACTIVATED FILTER
Call TokenNotActivated
For Each itm In Col
ActiveSheet.Range("A2:Z2").Select
Selection.AutoFilter Field:=6, Criteria1:=itm
' This is where the magic happens... creating the individual workbooks
Call TokenNotActivatedProcess
Next
ActiveSheet.AutoFilter.ShowAllData
End Sub

“ token 未激活”过滤器

Sub TokenNotActivated()    
'Col M = Yes
'Col U = provisioned
ThisWorkbook.Sheets(2).Activate
ActiveSheet.Range("A2:Z2").Select
Selection.AutoFilter Field:=13, Criteria1:="Yes"
Selection.AutoFilter Field:=21, Criteria1:="provisioned", Operator:=xlFilterValues
End Sub

运行进程以保存工作簿

Function TokenNotActivatedProcess()
Dim r As Range, n As Long, itm, FirstRow As Long
n = Cells(Rows.Count, 1).End(xlUp).Row
Set r = Range("A1:A" & n).Cells.SpecialCells(xlCellTypeVisible)
FirstRow = ActiveSheet.Range("F2").End(xlDown).Row
itm = ActiveSheet.Range("F" & FirstRow).Value
If r.Count - 2 > 0 Then Debug.Print itm & " - " & r.Count - 2
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.SaveAs Filename:="C:\Working\Testing\TokenNotActivated - " & itm + ".xls", FileFormat:=52, CreateBackup:=False
End Function

最佳答案

此错误是由于尝试过滤空范围而引起的。分析您的代码后,我的猜测是您在这里缺少工作表激活,因为在调用函数 TokenNotActivated 后重复行 ActiveSheet.Range("A2:Z2").Select 没有意义,并且也许您的代码正在尝试过滤一些空范围/工作表。

关于vba - Excel VBA 自动生成电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23595704/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com