Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA-表达式值在true IF语句后丢失类型和值_Vba_Excel - Fatal编程技术网

Excel VBA-表达式值在true IF语句后丢失类型和值

Excel VBA-表达式值在true IF语句后丢失类型和值,vba,excel,Vba,Excel,我在隐藏/取消隐藏行时遇到问题。出于某种原因,如果if语句中的任何一个最终为true,那么表达式值“i”将丢失其值和类型,并且我将得到一个类型不匹配错误。如果我在代码中没有I,只使用直接的数字,那么一切都很顺利。我似乎不知道如何解决这个问题,有什么建议吗?谢谢 这是有问题的代码 Sub Macro1() Dim i As Integer Dim j As Integer 'Initial Conditions i = 4 j = 184 If Range("A2").Value = "ONL

我在隐藏/取消隐藏行时遇到问题。出于某种原因,如果if语句中的任何一个最终为true,那么表达式值“i”将丢失其值和类型,并且我将得到一个类型不匹配错误。如果我在代码中没有I,只使用直接的数字,那么一切都很顺利。我似乎不知道如何解决这个问题,有什么建议吗?谢谢

这是有问题的代码

Sub Macro1()
Dim i As Integer
Dim j As Integer

'Initial Conditions
i = 4
j = 184

If Range("A2").Value = "ONLINE" Then
ActiveSheet.Rows("i:184").EntireRow.Hidden = False
End If

If Range("A2").Value = "OFFLINE" Then
ActiveSheet.Rows("i:184").EntireRow.Hidden = True
End If

End Sub​
ActiveSheet.Rows(“i:184”)
-这会将字符
i
传递到
Rows
,这是无效的

要使用
i
变量,请更改为
ActiveSheet.Rows(i&“:184”)
i
j
ActiveSheet.Rows(i&“:”&j)尝试以下操作:

 'provide the correct Column names as per your needs
 ActiveSheet.Range("A" & i & ":C" & j).EntireRow.Hidden
属性不接受代码中生成的字符串值参数。e、 g.Rows(“i:184”),这是一个类型无效的无效参数。因此,类型不匹配错误

如果活动工作表不再引用您最初指向的内容,这些行(4:184)将不起作用。因此,您应该始终使用工作表的
Range
对象的显式声明

对于更干净的代码,您可以这样使用它

Option Explicit

Public Sub Hide_Seek
Dim ws As Worksheet
Dim rng As Range
Dim checkVal as String

Set ws = ActiveWorkbook.Sheets("Sheet 1") 'whatever your sheet is
Set rng = ws.Range("A4") 'whatever starting cell, in your case it's D

'assuming these values do change    
i = 4
j = 184

'this is now resizing the range to your desired range, starting from the 
'initial range you defined
'Resize(Row, Column)
Set rng = rng.Resize(i, j)

checkVal = ws.Range("A2").Value
If checkVal = "ONLINE" then
   rng.EntireRow.Hidden = False
Elseif checkVal = "OFFLINE" then
   rng.EntireRow.Hidden = True
End If

End Sub

你是如何做到这一点的?
(“i:184”)
?就发布答案而言,你比我快,但我的评论还早;)