VBA LongVar = range.find 测试变量是否为空
VBA LongVar = range.find test if variable is empty
我有以下代码:
Dim wb As Workbook
Dim ws As Worksheet
Dim Test As String
Dim TestRow As Long
Dim LastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
Test = "Test"
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
TestRow = ws.Range("B1:B" & LastRow).Find(What:=Test).Row
'This was entered after the first error
If TestRow Is Empty Then
ws.Range("B" & LastRow + 1) = Test
End If
如果没有 If 语句并且我的数据中不存在测试,我会收到以下错误:'runtime 91 object variable or with block variable not set'.
接下来我想测试 TestRow 是否 empty/zero 我在 TestRow 上发现类型不匹配。我已经尝试过 Is Nothing 和其他各种选项,但我似乎无法让它工作。
有什么建议吗?
试试这个:
Dim wb As Workbook
Dim ws As Worksheet
Dim Test As String
Dim TestRow As Range
Dim LastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
Test = "Test"
LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
Set TestRow = ws.Range("B1:B" & LastRow).Find(What:=Test)
If TestRow Is Nothing Then
ws.Range("B" & LastRow + 1) = Test
Else
'Put code here if found Test (TestRow.Row is your row that it found it on)
End If
Find
喜欢 return 一个 Range
所以你需要 Dim
作为范围然后 Set
范围。
然后我们通过 TestRow Is Nothing
或 Not TestRow Is Nothing
检查它是否找到任何东西。
因为您想要该行,所以您将使用 TestRow.Row
作为它的行号。
我有以下代码:
Dim wb As Workbook
Dim ws As Worksheet
Dim Test As String
Dim TestRow As Long
Dim LastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
Test = "Test"
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
TestRow = ws.Range("B1:B" & LastRow).Find(What:=Test).Row
'This was entered after the first error
If TestRow Is Empty Then
ws.Range("B" & LastRow + 1) = Test
End If
如果没有 If 语句并且我的数据中不存在测试,我会收到以下错误:'runtime 91 object variable or with block variable not set'.
接下来我想测试 TestRow 是否 empty/zero 我在 TestRow 上发现类型不匹配。我已经尝试过 Is Nothing 和其他各种选项,但我似乎无法让它工作。
有什么建议吗?
试试这个:
Dim wb As Workbook
Dim ws As Worksheet
Dim Test As String
Dim TestRow As Range
Dim LastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
Test = "Test"
LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
Set TestRow = ws.Range("B1:B" & LastRow).Find(What:=Test)
If TestRow Is Nothing Then
ws.Range("B" & LastRow + 1) = Test
Else
'Put code here if found Test (TestRow.Row is your row that it found it on)
End If
Find
喜欢 return 一个 Range
所以你需要 Dim
作为范围然后 Set
范围。
然后我们通过 TestRow Is Nothing
或 Not TestRow Is Nothing
检查它是否找到任何东西。
因为您想要该行,所以您将使用 TestRow.Row
作为它的行号。