2016-04-12 93 views
1

下面是一個Sub,用於將所有單元格格式化爲電子表格中從工作單3開始的文本。你會看到有一條粗體的線,我很可能需要改變。該行的目的之一是保持Column1(「客戶端ID」)的值完好無損,因爲在每個表中它包含用此代碼轉換的'00001'值將更改爲'1'。這是錯誤的。重要的是每個工作表中的Column1總是包含相同的'00001'值。VBA將所有單元格格式化爲文本

Sub formatAllCellsAsText() 

Dim wsTemp As Worksheet 
Dim LastRow As Long 
Dim LastColumn As Long 
Dim StartCell As Range 
Dim Cell As Range 

For sht = 3 To Worksheets.Count 
    Set wsTemp = Sheets(sht) 
    Set StartCell = wsTemp.Range("A4") 
    LastRow = wsTemp.Range("A4").CurrentRegion.Rows.Count 
    LastColumn = wsTemp.Range("A4").CurrentRegion.Columns.Count 
    For Each Cell In wsTemp.Range(StartCell, wsTemp.Cells(LastRow, LastColumn)).Cells 

    If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value) 
    And InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 Then 

     Dim Temp As Double 
     Temp = Cell.Value 
     Cell.ClearContents 
     Cell.NumberFormat = "@" 
     Cell.Value = CStr(Temp) 
     End If 
    Next 
Next sht 

End Sub 

現在我的問題是,在一個工作表中有Column6(「值」),我想preseve千在數字前面。當我將行更改爲以下宏時,仍然會從Column6值中刪除前面的000。我想這種情況並不像我想象的那麼簡單。

If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value) And 
InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 And 
InStr(wsTemp.Cells(6, Cell.Column), "Value") <= 0 Then 

有什麼建議嗎?

+1

你可以改變格式如果您知道您的客戶端ID是一組字符數,則將單元格/列轉換爲自定義格式以顯示前導零。這樣你仍然可以把它看作一個數字。你可以通過VBA設置這種格式,但是在excel自定義格式中,如果你的客戶端代碼長度爲7位數,它將會像0000000一樣。 –

回答

1

請試試這個:

Sub formatAllCellsAsText() 
    Dim wsTemp As Worksheet 
    Dim LastRow As Long, LastColumn As Long 
    Dim StartCell As Range, Cell As Range 
    Dim Temp As Double 
    Dim Temp2 As String 
    For sht = 3 To Worksheets.Count 
    Set wsTemp = Sheets(sht) 
    Set StartCell = wsTemp.Range("A4") 
    LastRow = wsTemp.Range("A4").CurrentRegion.Rows.Count 
    LastColumn = wsTemp.Range("A4").CurrentRegion.Columns.Count 
    For Each Cell In wsTemp.Range(StartCell, wsTemp.Cells(LastRow, LastColumn)).Cells 
     If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value) And InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 Then 
     Temp = Cell.Value 
     Temp2 = Cell.NumberFormat 
     Cell.ClearContents 
     Cell.NumberFormat = "@" 
     Cell.Value = Format(Temp, Temp2) 
     End If 
    Next 
    Next 
End Sub 

您只需檢查爲數字格式,然後將其應用到字符串。這樣「0001」保持「0001」。另一種方法是使用.Text

Dim Temp As String 
Temp = Cell.Text 
Cell.ClearContents 
Cell.NumberFormat = "@" 
Cell.Value = Temp 

你也可以做到這一點只有If IsNumeric(Cell.Value) And Left(Cell.Text, 1) = "0" Then是真實的,那麼該規則只適用於具有前導零的數值細胞;)

0

每個工作表中的Column1始終包含相同的'00001'值。

更改線路

Cell.Value = CStr(Temp) 

Cell.Value = Format(Temp,"00000") 
相關問題