我正在尝试使用变量整数分配工作表引用。为了提供上下文,我导入数据,根据日期条件将数据拆分为不同的工作表,然后使用月份和年份命名工作表。
我后来希望能够比较不同表格中的数据,但技巧是我永远不会知道导入数据之前的日期范围。唯一的区别是整数变量,因为我正在创建工作表。下面我复制了与我的问题相关的部分代码。
Dim WS, WS1, WS2, WS3 As Worksheets
Dim Sheetname As String
Dim p, q, y As Integer
p = Worksheets.Count
For q = 1 To p
With Worksheets(q)
Sheetname = Format(st_date, "yyyy-mmm")
ActiveSheet.Name = Sheetname
End With
If q = 1 Then
Set WS1 = ThisWorkbook.Sheets(Sheetname)
End If
If q = 2 Then
Set WS2 = ThisWorkbook.Sheets(Sheetname)
End If
If q = 3 Then
Set WS3 = ThisWorkbook.Sheets(Sheetname)
End If
Next q
当我运行程序时,我必须设置WS3
时出现“类型不匹配”错误。我不确定为什么只有当它达到3时才这样做。
答案 0 :(得分:3)
您在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
逻辑通过 name 分配相关工作表。您可以用
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)
答案 1 :(得分:0)
试试这样:
Sub TestMe()
Dim WS As Worksheets, WS1 As Worksheets, WS2 As Worksheets, WS3 As Worksheets
Dim Sheetname As String
Dim p&, q&, y& 'shortwriting for dim q as long
For q = 1 To Worksheets.Count
With Worksheets(q)
.name = Format(st_date, "yyyy-mmm") & q
End With
If q = 1 Then
Set WS1 = ThisWorkbook.Worksheets(Sheetname)
End If
If q = 2 Then
Set WS2 = ThisWorkbook.Worksheets(Sheetname)
End If
If q = 3 Then
Set WS3 = ThisWorkbook.Worksheets(Sheetname)
End If
Next q
End Sub
我已更改With Worksheet.name
,因此非常有用。我已经添加了&q
,只是为了确保名称总是不同的。 Dims
根据评论中的想法进行了更改。