[英]excel - Loop through worksheet
I have never used Marcos in Excel before only in Access. 我从未在Excel中使用过Marcos,而仅在Access中使用过。 What I want to do is loop through the worksheet and where column X and Y are not null extract the information into a new worksheet. 我想做的是遍历工作表,其中X列和Y列不为空,将信息提取到新的工作表中。 But row Y may have more than 1 value and I would like to create a new record for each value in Y with X. each value is separated by a comma. 但是Y行的值可能不止1个,因此我想为X中的每个值创建一个新记录。每个值都用逗号分隔。
The result I would Like is 我想要的结果是
a C3 C3
a C4 C4
b C6 b C6
b C7 b C7
b C10 b C10
And so on 等等
Here is my code so far: 到目前为止,这是我的代码:
Sub Extract()
'
' Extract Macro
'
Dim WkSht As Worksheet, myOtherSheet As Worksheet, myBook As Workbook
Dim r As Integer
Dim Regex
Dim Match
Dim text
Set myBook = Excel.ActiveWorkbook
Set myOtherSheet = myBook.Sheets("New")
Set Regex = CreateObject("VBScript.RegExp")
Regex.Patten = """[^""]*""|[^,]*"
Regex.Global = True
j = 0
For Each WkSht In ThisWorkbook.Worksheets
If WkSht.Name = "Sheet1" Then
For r = 1 To 1000
If WkSht.Rows(r, B).Value <> "" & WkSht.Rows(r, G).Value <> "" Then
text = WkSht.Rows(r, G).Value
For Each Match In Regex.Execute(text)
myOtherSheet.Cells(j, 1).Value = WkSht.Cells(r, B)
myOtherSheet.Cells(j, 2).Value = Match
j = j + 1
Next Match
Exit For
End If
r = r + 1
Next r
Exit For
End If
Next WkSht
End Sub
Im unable to get this to run, I think my syntax is wrong for the regex, iv only ever used it in c#, Is this the best option for what I am trying to achieve, any help would be greatly appreciated ? 我无法运行它,我认为我的语法对于正则表达式是错误的,iv仅在c#中使用过,这是否是我想要实现的最佳选择,将不胜感激吗?
to fix the 1004 error, change 要修复1004错误,请更改
Rows(r, B).Value
to 至
Range(r, B).Value
the Rows property only takes a single index, you are trying to test a cell, so muct use either the Range or Cell object. Rows属性仅使用一个索引,您正在尝试测试单元格,因此muct使用Range或Cell对象。
also to make programming with RegEx easier, add a reference to the Microsoft VBScript Regular Expressions 5.5 library : 为了使RegEx编程更容易,请添加对Microsoft VBScript Regular Expressions 5.5库的引用:
on the Tools>References menu in the VB Editor. 在VB编辑器的“工具”>“参考”菜单上。
Then you can declare Dim Regex as RegExp
and use Set Regex = New RegExp
然后,您可以将Dim Regex as RegExp
声明Dim Regex as RegExp
并使用Set Regex = New RegExp
This will give you Intellisense which will help you code corerctly. 这将为您提供Intellisense,它将帮助您进行核心编码。
For a tutorial in using Regular expressions from Excel vba, see 有关使用Excel vba中的正则表达式的教程,请参见
Also, the in Tools>Options Editor tab, check all the boxes like Require Variable declaration and Auto List Members 另外,在“工具”>“选项编辑器”选项卡中,选中所有复选框,例如“ 需要变量声明”和“ 自动列表成员”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.