【发布时间】:2020-01-22 09:36:02
【问题描述】:
我正在编写一个读取文本文件 (test.txt) 并填写下拉列表的 Excel vba 脚本。 下拉列表包含以下项目:
苹果
梨
柠檬
石灰
文本文件有:
苹果
苹果片
大苹果
柠檬汁
柠檬
梨片
我想得到的是,当它在下拉列表中的文本文件中读取 Apple 切片时,它被设置为 Apple。当它读取 Big apple 时,下拉列表设置为 Apple。
这是我的代码
Sub CopyTXT()
Dim myFile, textline
Dim compare As String
Dim sArray() As String
Dim mywnd As Long
Dim i As Integer
Dim cell As Range
Dim dbsheet As Worksheet
Dim myArray() As Variant
Dim myTable As ListObject
Dim x As Long
Set myTable = Worksheets("Sheet2").ListObjects("Table3")
TempArray = myTable.DataBodyRange.Columns(1)
myArray = Application.Transpose(TempArray)
Set dbsheet = ThisWorkbook.Sheets("Sheet1")
lr = dbsheet.Cells(Rows.Count, 1).End(xlUp).Row
Charr = Chr$(160)
myFile = "test.txt"
For y = 1 To lr
If Not dbsheet.Cells(y, 1) = Charr Then
Close #1
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
For x = LBound(myArray) To UBound(myArray)
If InStr(1, textline, myArray(x), vbTextCompare) > 0 Then
dbsheet.Cells(y, 1).Value = textline
x = x + 1
End If
Next x
y = y + 1
Loop
End If
Next
Close #1
End Sub
【问题讨论】:
-
如果我理解正确,您的数组
myArray包含正确的单字值,如要填充到工作表的下拉列表中的值。在这种情况下,如果您将输入If InStr(1, textline, myArray(x), vbTextCompare) > 0 Then与数组中的项目匹配 - 您必须将数组中的值分配给单元格,而不是文本行:dbsheet.Cells(y, 1).Value = myArray(x)。 -
感谢您的快速回复。如果有 zoete aardapple (马铃薯),它现在在列表中部分修复了它,它与不正确的苹果匹配哈哈。