我有一個字符串數組。我也有一個包含兩列的工作表,第一列包含我的數組中的字符串,第二列包含與第一列關聯的數字代碼。 我需要爲數組的一個子集找到它們的相關代碼。我嘗試了以下,但它不起作用。搜索範圍內的數組數據類型字符串時出錯
Dim Data(1000, 1000) as string
.Range("B:B").Find(what:=Data(j,1), LookIn:=xlValues, SearchOrder:=xlByRows, MatchCase:=False).Row
我查看了爲什麼出現錯誤,我發現它不能識別數據(j,1),因爲它是字符串值。 Data(j,1)(對於j = 1)中的值是Sch_agr_Tor。如果我將數據(j,1)替換爲字符串「Sch_agr_Tor」,那很好,但是這不實際,因爲我想使用循環並且不能手動使用「find」。
在不久的窗口,我檢查,並得到如下:
? TypeName(Data(j,1))
String
? Data(j,1)
Sch_agr_Tor
? Data(j,1)="Sch_agr_Tor"
False
? Data(j,1)=Sch_agr_Tor
False
我想這可能是查找內部錯誤。所以我寫了自己的find函數。
Function FindRow(Rng As Range, Exp As String) As Long
Dim vArr As Variant
Dim j As Long
Dim n As Long
Dim c As Range
n = 0
For Each c In Rng
If Exp = c.value Then
n = c.Row
Exit For
End If
Next c
FindRow = n
End Function
但是現在,當我改變「EXP作爲字符串」的論調中,將返回0,FindRow功能「EXP爲Variant」。
n = FindRow(UserSheet.Range(Cells(1, 2), Cells(Cells(Rows.Count, 2).End(xlUp).Row, 2)), Data(j, 1))
如果我進入
n = FindRow(UserSheet.Range(Cells(1, 2), Cells(Cells(Rows.Count, 2).End(xlUp).Row, 2)), "Sch_agr_Tor")
我找到正確答案,這是39 這裏是頭和其餘代碼:
Option Explicit
Option Base 1
Sub main()
Dim MainWorkbook As Workbook
Dim MainSheet, UserTableSheet, InputSheet, OutputSheet, TradesSheet, InitialSheet As Worksheet
Dim targetCellLoc As String
Dim fileName As String
Dim addressName As String
Dim originCellLoc, Str As String
Dim i, j, NumRuns As Integer
Dim t_start, t_end As Double
Dim FirstCol, LastCol, n As Integer
Dim Data() As Variant
' Initialize the variables
Set MainWorkbook = Application.ThisWorkbook
Set InitialSheet = MainWorkbook.ActiveSheet
Set MainSheet = MainWorkbook.Sheets("Sheet1")
i = 2
Do While MainSheet.Cells(11, i).value <> ""
Set UserTableSheet = MainWorkbook.Sheets(MainSheet.Cells(11, i).value)
Set InputSheet = MainWorkbook.Sheets(MainSheet.Cells(12, i).value)
With InputSheet
FirstCol = .Range("1:1").Find(what:="Collateral Agreement Group:", LookIn:=xlValues, SearchOrder:=xlByColumns, MatchCase:=False).Column
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'creating an array for our data with the right dimension
ReDim Data(LastCol - FirstCol + 1, 6)
For j = 1 To UBound(Data, 1)
Data(j, 1) = Mid(InputSheet.Cells(1, FirstCol + j - 1).value, 28, 1 + Len(InputSheet.Cells(1, FirstCol + j - 1).value) - 28)
MainWorkbook.Sheets("Sheet4").Cells(j, 1) = Data(j, 1)
n = FindRow(UserTableSheet.Range(Cells(2, 2), Cells(Cells(Rows.Count, 2).End(xlUp).Row, 2)), Data(j, 1))
Data(j, 2) = UserTableSheet.Cells(n, 4)
Next j
i = i + 1
Loop
End Sub
你得到什麼錯誤,你有什麼調用'.Range'上? – Comintern
錯誤類型不匹配。範圍之前有父母指的是正確的工作表。 –
然後你應該在更多的上下文中發佈代碼。我無法用上面的代碼複製錯誤。 – Comintern