excel - Excel VBA:单列:在下面查找文本,复制文本和其他行的文本,在第二个选项卡上转置为列
问题描述
我有一个非常具体的 VBA 需求:从单列数据创建数据表。
在列中查找文本,复制/粘贴,然后向下删除 x 行,复制/粘贴,然后向下删除 x 行,复制/粘贴等。我有一列数据 A:A
- Sheet1:查找文本“MyText”,复制“MyText”,粘贴到Sheet2,A2
- Sheet1:从“MyText”,删除5行,复制文本,粘贴到Sheet2,B2
- Sheet1:从“MyText”,删除8行,复制文本,粘贴到Sheet2,C2
- Sheet1:从“MyText”,删除16行,复制文本,粘贴到Sheet2,D2
然后循环查找下一个“MyText”并粘贴到 A3 中,依此类推。
谢谢!查理·E
解决方案
请尝试下一个代码:
Sub CopyMyTextReferences()
Dim sh As Worksheet, sh2 As Worksheet, i As Long, MyText As String, rngTxt As Range
Dim rng As Range, rng2 As Range, lastRow As Long, lastR As Long, strFirstAddr As String
Set sh = ActiveSheet 'use here your sheet to copy from
Set sh2 = Worksheets("Sheet2") 'use here your sheet where to copy
MyText = "testStr" 'use here your string to be searched
lastRow = sh.Range("A" & Rows.count).End(xlUp).Row
Set rng = sh.Range("A2:A" & lastRow)
Set rngTxt = rng.Find(MyText, sh.Range("A2"), xlValues, xlWhole)
If Not rngTxt Is Nothing Then
strFirstAddr = rngTxt.Address
Do
lastR = sh2.Range("A" & Rows.count).End(xlUp).Row + 1
Set rng2 = sh2.Range("A" & lastR)
With rng2
.Value = rngTxt.Offset(4).Value
.Offset(1).Value = rngTxt.Offset(5).Value
.Offset(2).Value = rngTxt.Offset(8).Value
.Offset(3).Value = rngTxt.Offset(16).Value
'.Offset(4).Value = rngTxt.Offset(xx).Value
End With
Set rngTxt = rng.FindNext(After:=rngTxt)
Loop Until rngTxt.Address = strFirstAddr
Else
MsgBox MyText & " could not be found...": Exit Sub
End If
End Sub
推荐阅读
- json - “对象”类型上不存在属性“位置”
- php - 无法使用 PHP 7.2 从 MySQL 数据库中选择数据
- r - 正则表达式 - 匹配两个两位数之间所有值的最佳方法?
- sql - 如何根据另一列计算行数?
- django - 没有对象的 Django ManyToMany 相关管理器返回 True
- node.js - Mongoose 模型#聚合函数返回 0
- azure - Azure:代理已收到关闭信号。当代理服务停止或手动启动的代理被取消时,可能会发生这种情况
- data-recovery - 分区格式 f2fs 后恢复数据
- node.js - 使用 POST 将文件从 HTML5 网页上传到 Node.js 服务器
- python - Pandas read_table() -- 如何使用多种自定义 NA 格式?