我正在尝试使用变量整数分配工作表引用。为了提供上下文,我导入了数据,根据日期标准将数据拆分到不同的工作表中,然后使用月份和年份命名工作表。
后来我希望能够比较不同工作表中的数据,但诀窍是在导入数据之前我永远不会知道日期范围是什么。唯一的区别是我创建工作表时的整数变量。下面我复制了与我的问题相关的部分代码。
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 时才会这样做。
最佳答案
您只在 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)
关于vba - 将变量分配给工作表 : VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543279/