用于编辑字符串并将其写入其他 sheet 的宏

Macro to edit strings and write them on other sheet

我是编程新手,我很难弄清楚如何完成我的任务。

我有一个模板sheet,它的组织方式是在填充后将其转换为“.csv”,然后导入到构建数据库的程序中。

我还有另一个 Sheet,其中包含一些我需要的数据和一些我不需要的数据。 我要阅读的第一列是遵循上述模型的 "Tag Names":

标签名称 /// 低 /// 高 /// ELU

80-PIT-0001 /// 0 /// 1 /// C

32-XI-004B /// 1 /// 0 /// C

45-CIT-4001 /// 0 /// 1 /// D

我需要获取所有这些标签并且:

a) 从标签名称中删除“-” b) 在模板中写入不带“-”的标签名称 sheet c) 将其写入模板时 sheet 必须在标签名称末尾添加“_PV”和“_PB”。每个人都需要在不同的行中。 d) 还需要复制所有属性

就像这样:

80PIT0001_PV /// 0 /// 1 /// C

80PIT0001_PB /// 0 /// 1 /// C

32XI004B_PV /// 1 /// 0 /// C

32XI004B_PB /// 1 /// 0 /// C

45CIT4001_PV /// 0 /// 1 /// D

45CIT4001_PB /// 0 /// 1 /// D

如果有人能告诉我如何正确操作和编辑这些字符串以及如何将它们写入新的 sheet,在我的例子中,模板 sheet.

我真的很感谢任何愿意帮助我的人。

好吧,您并不完全需要编程来实现这一点。这可以使用 Excel 和 Google 工作表中的公式来实现。 Substitute 公式将删除“-”,并结合 IFROW 连接公式将添加'_PV'。 Arrayformula 在这些其他公式之上将在整个列中执行此计算,而无需每次都向下拖动公式。

未经测试,在手机上写的,但可能是这样的。我假设您的数据(不包括 headers/names 列)在名为 'Source' 的 sheet 单元格 A2 中开始 - 并且数据是 A 列是连续的。

在 运行 代码之前保存工作簿的副本,因为代码将尝试覆盖 sheet 'Template' 上的数据(假设它存在)。

Option Explicit

Sub FillTemplateSheet()

With Thisworkbook

' Change this to whatever sheet your data is on and change cell reference to the first tag name (excluding header) '
With .worksheets("Source").range("A2")

Dim lastRow as long
lastRow = .end(xldown).row ' This is not the best way to find the last row, but might work in your use case '

Dim arrayOfValues() as variant
arrayOfValues = .resize(lastRow - .row+1, 4).value2 ' Assumes we want the first four columns '

End with

Dim rowIndex as long
Dim columnIndex as long
Dim alteredTagName as string

' Appending PV and PB to each tag name means we basically need twice as many body rows in the output.'

Dim outputArray() as variant
Redim outputArray(lbound(arrayOfValues,1) to (ubound(arrayOfValues,1)*2), lbound(arrayOfValues,2) to ubound(arrayOfValues,2))

For rowIndex = lbound(arrayOfValues,1) to ubound(arrayOfValues,1)

For columnIndex = lbound(arrayOfValues,2) to ubound(arrayOfValues,2)

If columnIndex <> 1 then
' d) copy all other attributes to outputArray'

outputArray(rowIndex, columnIndex) = arrayOfValues(rowIndex,columnIndex)

outputArray(rowIndex+1, columnIndex) = arrayOfValues(rowIndex,columnIndex)

Else

alteredTagName = arrayOfValues(rowIndex,columnIndex) 

'a) get rid of all - '
alteredTagName = vba.strings.join(VBA.strings.split(alteredTagName,"-",-1,vbbinarycompare),vbnullstring)

'b) write to output array '
'c) append PV and PB '

outputArray(rowIndex, columnIndex) = alteredTagname & "_PV"

outputArray (rowIndex +1, columnIndex) = alteredTagName & "_PB"

End if

Next columnIndex

Next rowIndex

End with

' Assumes headers are on row 1 of sheet Template, and therefore first tag name will be in cell A2'
.worksheets("Template").range("A2").resize(ubound(outputArray,1),ubound(outputArray,2)).value2 = outputArray

End with

End sub