如何使用列号引用Excel列而不是列字母

时间:2017-04-07 12:49:32

标签: vb.net excel-interop

以下代码有效:

Imports Microsoft.Office.Interop

Dim xlApp As New Excel.Application
xlApp.Visible = True

Dim wb1 As Excel.Workbook
wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

Dim ws1 As Excel.Worksheet
ws1 = CType(wb1.Sheets(1), Excel.Worksheet)  

With ws1
     CType(.Columns("K:XFD"), Excel.Range).NumberFormat = "General"
End With

我想使用列号而不是列号。

这是我尝试的但它不起作用:

With ws1
      CType((.Columns(11), .Columns(.Columns.Count)), Excel.Range)).NumberFormat = "General"
End With

2 个答案:

答案 0 :(得分:0)

通常,您可以使用整数。您应该只访问Range属性,并传递两个Cell引用。

Dim a, b, c, d As Integer

With ws1
    .Range(.Cells(a, b), .Cells(c, d)).NumberFormat = "General"
End With

,其中

enter image description here

以下是您的具体解决方案

With ws1
    Dim a, b, c, d As Integer
    a = 1 ' row 1
    b = 11 ' column k
    c = .Rows.Count ' the last row
    d = .Columns.Count ' the last column
    .Range(.Cells(a, b), .Cells(c, d)).NumberFormat = "General"
End With

由于Range获取对象,您可以将整数索引和字符串传递给Cells。这可能在将来有所帮助。

With ws1
    Dim a, b, c, d As Object
    a = 1 ' row 1
    b = "k" ' column k
    c = .Rows.Count
    d = .Columns.Count
    .Range(.Cells(a, b), .Cells(c, d)).NumberFormat = "General"
End With

答案 1 :(得分:0)

我首先想了解你正在做什么,所以我使用了这段代码:

With ws1
    CType(.Columns("K:XFD"), Excel.Range).Select()
End With

这会突出显示从K到XFD的所有行。

所以考虑到这一点。如果要使用数字而不是字母,请使用以下代码:

With ws1
    .Range(.Cells(1, 11), .Cells(.Rows.Count, .Columns.Count)).NumberFormat = "General"
End With

再次测试它是否正如你使用它之后所做的那样:

With ws1
    .Range(.Cells(1, 11), .Cells(.Rows.Count, .Columns.Count)).Select()
End With