将VBA数组转换为VB.NET

时间:2015-10-26 21:10:56

标签: arrays vb.net excel vba

我一直在尝试创建一个VB.NET VTSO插件,其中根据列标题值重新排列excel列。

我发现(在线)VBA代码确实如此,但Visual Basic无法识别“Dim v = ...”行。

有谁知道如何解决这个问题。

Dim v As Object, x As Object, findfield As Object
    Dim oCell As Excel.Range
    Dim iNum As Long

    Dim v = Array("First Name", "Middle Name", "Last Name", "Date of Birth", "Phone Number", "Address", "City", "State", "Postal (ZIP) Code", "Country")
    For x = LBound(v) To UBound(v)
        findfield = v(x)
        iNum = iNum + 1

        oCell = ActiveSheet.Rows(1).Find(What:=findfield, LookIn:=Excel.XlFindLookIn.xlValues, LookAt:=Excel.XlLookAt.xlWhole, SearchOrder:=Excel.XlSearchOrder.xlByRows, SearchDirection:=Excel.XlSearchDirection.xlNext, MatchCase:=False, SearchFormat:=False)

        If Not oCell.Column = iNum Then
            ThisApplication.ThisWorkbook.Columns(oCell.Column).Cut
            ThisApplication.ThisWorkbook.Columns(iNum).Insert(Shift:=Excel.XlInsertShiftDirection.xlShiftToRight)
        End If
    Next x

1 个答案:

答案 0 :(得分:1)

蒂姆通过对修复的评论将其钉在头上。

    Dim v As String() = New String(9) {"First Name", "Middle Name", "Last Name", "Date of Birth", "Phone Number", "Address", "City", "State", "Postal (ZIP) Code", "Country"}

Array Class是一个抽象类,意味着你不能直接初始化它,而是必须通过它的一个子节点(另一个继承它的类)来实现它。在.Net中,您必须指定数组的基础类型(对象计数),通常通过在变量声明中的类型后面添加括号。