【发布时间】:2015-12-31 06:12:27
【问题描述】:
您好 StackOverflow 社区:
我想在我的工作簿中的三个特定工作表上循环浏览同一列。我知道代码行中需要一些类似于 here 和 here 发布的代码,但我似乎无法让它们工作,而是收到错误 '1004'、“Application-defined or对象定义的错误”。
附加说明:我在声明之后输入了“For each ws in this Workbook.sheets”,并在“End Sub”之前的最后输入了“Next”。我还在下面的代码中尝试了“r=1”之后的处理代码,并收到了相同的 1004 错误。我在循环代码之后用“Next”尝试了这个,它仍然只循环通过第一张纸。
这是代码:
Sub MakeWordList()
Dim InputSheet As Worksheet
Dim WordListSheet As Worksheet
Dim PuncChars As Variant, x As Variant
Dim i As Long, r As Long
Dim txt As String
Dim wordCnt As Long
Dim AllWords As Range
Dim PC As PivotCache
Dim PT As PivotTable
Application.ScreenUpdating = False
Set InputSheet = ActiveSheet
Set WordListSheet = Worksheets.Add(after:=Worksheets(Sheets.Count))
WordListSheet.Range("A1") = "All Words"
WordListSheet.Range("A1").Font.Bold = True
InputSheet.Activate
wordCnt = 2
PuncChars = Array(".", ",", ";", ":", "'", "!", "#", _
"$", "%", "&", "(", ")", " - ", "_", "--", "+", _
"=", "~", "/", "\", "{", "}", "[", "]", """", "?", "*")
r = 1
' Loop until blank cell is encountered
Do While Cells(r, 7) <> ""
' covert to UPPERCASE
txt = UCase(Cells(r, 7))
' Remove punctuation
For i = 0 To UBound(PuncChars)
txt = Replace(txt, PuncChars(i), "")
Next i
' Remove excess spaces
txt = WorksheetFunction.Trim(txt)
' Extract the words
x = Split(txt)
For i = 0 To UBound(x)
WordListSheet.Cells(wordCnt, 1) = x(i)
wordCnt = wordCnt + 1
Next i
r = r + 1
Loop
' Create pivot table
WordListSheet.Activate
Set AllWords = Range("A1").CurrentRegion
Set PC = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, _
SourceData:=AllWords)
Set PT = PC.CreatePivotTable _
(TableDestination:=Range("C1"), _
TableName:="PivotTable1")
With PT
.AddDataField .PivotFields("All Words")
.PivotFields("All Words").Orientation = xlRowField
End With
End Sub
有什么方法可以循环浏览我的前三张纸或识别我想要循环浏览的纸吗?具体来说,我想遍历前三张纸的 G 列。
【问题讨论】:
-
你有一些数据可以用来评估你的功能吗? IE。我可以查看您的功能,但无法确定它如何与您的数据交互?另一方面,您使用 For i=0 to ubound(array) 这很好,更好的是 For i=Lbound(array) to ubound(array) 这将防止超出范围的错误:-) 提供一些列数据,您使用起来会更容易适应吗?