你只得到WS3
类型不匹配错误的原因是因为你是如何定义WS1
,WS2
和WS3
。该生产线
Dim WS, WS1, WS2, WS3 As Worksheets
相当于线
Dim WS As Variant, WS1 As Variant, WS2 As Variant, WS3 As Worksheets
问题:
- 你不是故意的申报大多数这些对象的其变
- 因为它们被声明为变种,他们可以愉快地分配到您的循环中的工作表对象,没有错误
Worksheets
是错误的对象类型,您想使用Worksheet
对象。
- 因为(仅)
WS3
是错误的对象类型,所以会引发类型不匹配错误!
的代码应该是:
' Declare variable types individually
Dim WS As Worksheet, WS1 As Worksheet, WS2 As Worksheet, WS3 As Worksheet
Dim Sheetname As String
' Longs can be bigger than Integers, unless memory is a big issue can use Longs by default
' Also declare individually
Dim p As Long, q As Long, y As Long
' Fully qualifying the sheets by using a workbook object
p = ThisWorkbook.Worksheets.Count
For q = 1 To p
' You never changed st_date, so are trying to name all sheets the same
' st_date = ...
Sheetname = Format(st_date, "yyyy-mmm")
' The active sheet doesn't change, no need for With block for single statement
ThisWorkbook.Worksheets(q).Name = Sheetname
' Use ElseIf statements for quicker evaluation and neater code
If q = 1 Then
Set WS1 = ThisWorkbook.Sheets(Sheetname)
ElseIf q = 2 Then
Set WS2 = ThisWorkbook.Sheets(Sheetname)
ElseIf q = 3 Then
Set WS3 = ThisWorkbook.Sheets(Sheetname)
End If
Next q
改进
我真的不知道为什么你根据表q
分配表名称,但随后用If
逻辑来分配相关工作表由名称。你也许可以用一些替换代码像
Dim WS1 As Worksheet, WS2 As Worksheet, WS3 As Worksheet
Dim Sheetname As String
Dim p As Long, q As Long,
p = ThisWorkbook.Worksheets.Count
For q = 1 To p
' You never changed st_date, so are trying to name all sheets the same
' st_date = ...
Sheetname = Format(st_date, "yyyy-mmm")
ThisWorkbook.Worksheets(q).Name = Sheetname
Next q
Set WS1 = ThisWorkbook.Sheets(1)
Set WS2 = ThisWorkbook.Sheets(2)
Set WS3 = ThisWorkbook.Sheets(3)
'昏暗的WS,WS1,WS2,WS3作为Worksheets'是一个错误,你需要定义每个对象的工作表。正确的定义语法是'Dim WS As Worksheet,WS1 As Worksheet,WS2 As Worksheet,WS3 As Worksheet'。同样,'Dim p,q,y As Integer', –
您的代码中的活动工作表永远不会改变(至少是您发布的位),'st_date'也不会,并且您的With子句毫无意义。 – SJR