vba - 为什么我会遇到“类型不匹配”错误?
问题描述
我正在尝试编写一个 VBA 函数,该函数将包含两列的表作为输入。我想返回第 2 列中对应的第 1 列中的行为 3 的元素。基本上相当于where
SQL 中的子句。
代码的逻辑似乎很好,但是我收到类型不匹配错误。我声明了函数As Variant
,我想返回的数组也是As Variant
如此。
Function FilterTable(tableName As String) As Variant
Dim table As range
Dim cell As range
Dim names As range
Dim i As Integer
Dim names_2(100) As Variant
Dim j As Integer
Dim test As String
i = 1
j = 1
Set table = ActiveSheet.range(tableName).Columns(1)
Set names = ActiveSheet.range(tableName).Columns(2)
For Each cell In table.Cells
If cell = 3 Then
names_2(i) = names.Cells(j, 1).Value
i = i + 1
End If
j = j + 1
Next
FilterTable = names_2
End Function
为什么会出现类型不匹配错误,我该如何解决?
解决方案
There are a few problems with your code but nothing that should cause a type mismatch unless you have worksheet errors (e.g. #N/A, #DIV/0!, etc) in your data.
You should be aware of what worksheet your table is on; don't rely on activesheet.
A 1-D array defaults as zero-based, not one-based.
You should remove the excess (empty) elements in your array after populating it. Use the Locals window or set a Watch on your array to see it populate and resize as you step through the function with F8.
Option Explicit
Sub main()
Dim n As Variant, i As Long
n = FilterTable("table1")
For i = LBound(n) To UBound(n)
Debug.Print n(i)
Next i
End Sub
Function FilterTable(tableName As String) As Variant
Dim table As Range, names As Range, cell As Range
Dim i As Long, j As Long
Dim names_2 As Variant
i = 0
j = 1
ReDim names_2(100)
Set table = Worksheets("Sheet3").Range(tableName).Columns(1)
Set names = Worksheets("Sheet3").Range(tableName).Columns(2)
For Each cell In table.Cells
If Not IsError(cell) Then
If cell = 3 Then
names_2(i) = names.Cells(j, 1).Value
i = i + 1
End If
End If
j = j + 1
Next cell
ReDim Preserve names_2(i - 1)
FilterTable = names_2
End Function
推荐阅读
- python - 在 OSMNX ox.plot_graph_routes() 中更改图形大小
- r - 如何更改 R 中 reReg 包中 plotEvents 中线条的颜色?
- react-native-ios - 错误:预期节点是 ["Statement"] 类型,但得到了 "AssignmentExpression" | 反应原生 IOS
- continuous-integration - 有没有办法通过 GitHub Actions 的内置容器功能缓存容器下载?
- javascript - 使用 Mongodb 聚合获取所有订单中产品的总订购数量
- python - 更快地在应用程序中运行 Python 或导入 CSV
- c - 同一个key的shmget缓冲区和semget semaphore有什么关系?
- cuda - GPGPU中的分支分歧
- soundcloud - SoundCloud API“可下载”搜索过滤器
- sql - 相关子查询中的内部查询别名