gpt4 book ai didi

excel - VBA InStr 与 Excel 工作表中的标准

转载 作者:行者123 更新时间:2023-12-04 20:23:06 24 4
gpt4 key购买 nike

我仍然是使用 VBA 语言的新手。我需要有关 InStr 方法的帮助,我试图在 Excel 工作表范围内制定我的标准。

Sub AddressCode()
Dim lastrow As Long
Dim i As Integer, icount As Integer

lastrow = ActiveSheet.Range("A30000").End(xlUp).Row
For i = 1 To lastrow
If InStr(1, (Range("A" & i)), "Taman") <> 0 Then
icount = icount + 1
Range("H" & icount & ":L" & icount) = Range("A" & i & ":E" & i).Value
End If
Next i
End Sub

Instr example

如何将结果列为我的标准,并且结果与我的行地址有偏移。例如,A 列:Alex 在公园慢跑。标准列表:慢跑、运行、跳跃等。

结果是A 列 Alex 在公园慢跑,B 列慢跑

最佳答案

复制带条件的行范围

快速修复

Sub AddressCode()

Dim ws As Worksheet: Set ws = ActiveSheet

Dim LastRow As Long: LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
' Or:
'LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

Dim i As Long, icount As Long

' The VBA constant 'vbTextCompare' means e.g. "Taman" = "TaMaN"
' The VBA constant 'vbBinaryCompare' means e.g. "Taman" <> "TaMaN"

For i = 1 To LastRow
If InStr(1, ws.Range("A" & i).Value, "Taman", vbTextCompare) > 0 Then
icount = icount + 1
ws.Range("H" & icount & ":L" & icount).Value _
= ws.Range("A" & i & ":E" & i).Value
End If
Next i

End Sub

范围和常量

  • 下面说明了让它适用于常量的其他值是多么容易。和他们一起玩,但要小心:不可撤销。
Sub AddressCodeRangeAndConstants()

Const sFirst As String = "A1"
Const sCriteria As String = "Taman"
Const dfirst As String = "H1"
Const nCols As Long = 5

Dim ws As Worksheet: Set ws = ActiveSheet

Dim slCell As Range
Set slCell = ws.Cells(ws.Rows.Count, ws.Range(sFirst).Column).End(xlUp)
Dim srg As Range: Set srg = ws.Range(sFirst, slCell)

Dim drg As Range: Set drg = ws.Range(dfirst).Resize(, nCols)

Dim sCell As Range
For Each sCell In srg.Cells
If InStr(1, sCell.Value, sCriteria, vbTextCompare) > 0 Then
drg.Value = sCell.Resize(, nCols).Value
Set drg = drg.Offset(1)
End If
Next sCell

End Sub

关于excel - VBA InStr 与 Excel 工作表中的标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67834360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com