简体   繁体   English

Excel VBA用另一个值替换列值?

[英]Excel VBA to replace column values with another value?

I have a worksheet with around 3,000 rows. 我有一个大约3,000行的工作表。 One of these columns contains ethnicity data but it is in numeric format, rather than text format, eg: 其中一列包含种族数据,但它采用数字格式,而不是文本格式,例如:

  • 1 = American Indian or Alaskan Native 1 =美洲印第安人或阿拉斯加原住民
  • 2 = Asian, Asian American, or Pacific Islander 2 =亚洲,亚裔美国人或太平洋岛民
  • 3 = African American or Black 3 =非裔美国人或黑人
  • 4 = Mexican or Mexican American 4 =墨西哥或墨西哥裔美国人

I'd like to write a module in VBA that uses a Select Case (or...?) to swap out the values in this column from the integer to text. 我想在VBA中编写一个使用Select Case(或......?)的模块,将此列中的值从整数换成text。 Can someone show me how to accomplish this? 有人能告诉我如何实现这一目标吗?

Excel中的非VBA(在我看来更简单)方法是创建一个包含该数据的查找表 - 第一列中的整数,第二列中的文本,然后是数据旁边的列,使用VLOOKUP找到相应的文字。

Heres a quick VBA mashup that will replace your Current Selection values with substitutes: 下面是一个快速的VBA mashup,用替换代替你的Current Selection值:

Option Explicit
Option Base 1

Public Sub ReplaceData()

    Dim RangeCells As Range

    Dim LookupArray(4) As String, RangeCell As Range

    LookupArray(1) = "Test A"
    LookupArray(2) = "Test B"
    LookupArray(3) = "Test C"
    LookupArray(4) = "Test D"

    For Each RangeCell In Selection

        If IsNumeric(RangeCell.Value) And RangeCell.Value <= UBound(LookupArray) And RangeCell.Value >= LBound(LookupArray) Then
            RangeCell.Value = LookupArray(Val(RangeCell.Value))
        End If

    Next RangeCell

End Sub

Assumptions: all possible cell values are covered in array index. 假设:所有可能的单元格值都包含在数组索引中。 Otherwise select case is probably what you want to switch to. 否则,选择大小写可能就是您要切换到的大小写。 Let me know if you can't figure how to switch to that. 如果您无法想出如何切换到那个,请告诉我。

Hope this solves your problem. 希望这能解决你的问题。

To do something like VLOOKUP, but with replacement you can try the below 要做一些类似VLOOKUP的事情,但有了替换,你可以尝试以下

Option Explicit
Sub ReplaceData()

Dim i As Integer
Dim ABCArray() As Variant, DEFArray As Variant

    ABCArray = Array("A", "b", "C")
    DEFArray = Array("D", "E", "F")

    With ActiveSheet.Range("A:A")

        For i = LBound(ABCArray) To UBound(ABCArray)

            .Replace What:=ABCArray(i), _
            Replacement:=DEFArray(i), _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            MatchCase:=False

        Next i

    End With
End Sub

I cannot agree with VLOOKUP being better for one simple reason: we do macros to automate repeating actions and I assume someone is looking for macro solution mostly in cases like that. 我不能同意VLOOKUP更好的一个简单的原因:我们做宏来自动重复动作,我认为有人正在寻找宏解决方案,主要是在这种情况下。

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

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