简体   繁体   English

Excel VBA - 子串和粘贴

[英]Excel VBA - Substring & Paste

I have a column that has US state abbreviations (MI, NY, FL, etc.). 我有一个列有美国州缩写(MI,NY,FL等)。 I have an issue where there is an observation that is listed as "NJ NJ". 我有一个问题,有一个被列为“NJ NJ”的观察。 This observation moves around within the same column each week. 这种观察每周在同一列内移动。

I want to create a macro that substrings each observation to two characters and just drops everything afterwords. 我想创建一个宏,将每个观察结果分为两个字符,然后删除所有后续字。

Would I be able to use the Mid function to grab the first two characters, and then paste it overtop of the original value. 我是否可以使用Mid函数来抓取前两个字符,然后将其粘贴到原始值的上方。 Further, would it be appropriate to offset by one or is there a way to do it all at once? 此外,是否适合偏移一个或是否有办法一次完成所有操作?

Thanks! 谢谢!

Assuming you have your List in the 1st Column, starting at Row 1, the following Macro will do it. 假设您在第1列中有列表,从第1行开始,以下宏将执行此操作。 Obviously you can make a lot of improvements and error checks to the code, but this should get you started. 显然,您可以对代码进行大量改进和错误检查,但这应该可以帮助您入门。

Sub FixStates()

Dim lRow As Long
Dim lCol As Long
Dim strContent As String

    lRow = 1
    lCol = 1

    Do While Cells(lRow, lCol) <> ""
        strContent = Trim(Cells(lRow, lCol))
        If Len(strContent) > 2 Then Cells(lRow, lCol) = Left(strContent, 2)
        lRow = lRow + 1
    Loop

End Sub

If you want your result to be offset by one cell from the source cell, then the formula by Daniel Cook works fine. 如果你希望你的结果被源单元格中的一个单元格偏移,那么Daniel Cook的公式可以正常工作。

On the other hand, if you want your result to overwrite the source cell, you would have to copy the cell with the result (using the same formula as above) and paste-special as value on top of the source cell (you can do this for many cells at once), or write a VBA sub. 另一方面,如果您希望结果覆盖源单元格,则必须使用结果复制单元格(使用与上面相同的公式)并在源单元格顶部粘贴特殊值(您可以执行此操作)这对于许多单元一次),或写一个VBA子。

I personally find it simpler the "copy and paste-special as value" way. 我个人觉得“复制和粘贴特殊的价值”方式更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM