2017-04-07 41 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 
相關問題