2017-04-07 33 views
0

下面的代码工作的Excel列:如何使用列数来引用,而不是列字母

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 
+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

我首先想了解你究竟做什么,它是那么我用这个代码:

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 
相关问题