用于读取 xls 和操作单元格的 VBA 脚本代码



我有一个只有一个工作表的Excel工作表。此 Excel 工作表的第一行具有列的标题。

工作表在以下列中包含数据和 n 行数:

列: A |乙 |C |D |E |F |G |H

  1. 首先,我正在创建文件的副本并重命名它 - 这有效!

    'Copy and rename the file
    Dim sourceFile As String, destFile As String
    sourcePath = Range("D6")
    destFile = Split(sourcePath, ".")(0) + "_Formated.xls"
    FileCopy sourcePath, destFile
    
  2. 我想通过VBA代码阅读此destFile Excel工作表。我将进行一些单元格操作,因此请给我一个工作代码来了解如何读取整个工作表以及如何在 for 循环中访问特定行。

  3. 我还想知道通过VBA代码向此destFile excel工作表添加新列标题和值的代码。

  4. 仅通过VBA代码清除单元格值而不删除单元格的代码是什么。

  1. 我想通过VBA代码阅读此destFile Excel工作表。我将进行一些单元格操作,因此请给我一个工作代码来了解如何读取整个工作表以及如何在 for 循环中访问特定行。
dim sh as Worksheet
set sh =  Workbooks.Open(destFile).Worksheets(1)
  1. 我还想知道通过VBA代码向此destFile excel工作表添加新列标题和值的代码。
sh.rows(1).Insert Shift := xlDown
ThisWorkbook.Worksheets(1).Rows(1).Copy sh.Rows(1)
  1. 仅通过VBA代码清除单元格值而不删除单元格的代码是什么。
sh.Range("A1").Value = ""

我设法用下面的代码完成了这项工作。这是最糟糕的编码方式,看起来并不复杂,但它可以完成工作。谢谢!

Sub Format()
'Copy and rename the file
Dim SourceFile As String, DestFile As String
SourceFile = Range("D6")
SourceString = Range("D3")
TestSuiteName = Range("D2") & ""
DestFile = Split(SourceFile, ".")(0) + "_Formated.xls"
On Error GoTo ErrorHandler:
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FileExists(DestFile) Then
    FileCopy SourceFile, DestFile
End If
'Read DestFile worksheet content
Dim wks As Worksheet
Set wks = Workbooks.Open(DestFile).Worksheets(1)
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
    If Cells(i, 6).Value = "Step 1" Then
        Cells(i, 7) = "Other_Migration_Fields" & Cells(i, 7) & vbLf & vbLf & "QC Path:" & Cells(i, 8)
        Cells(i, 8) = Replace(Cells(i, 8), SourceString, TestSuiteName)
    Else
        Cells(i, 1) = ""
        Cells(i, 2) = ""
        Cells(i, 7) = ""
        Cells(i, 8) = ""
    End If
Next i
ErrorHandler:
    Msg = "Error # " & Str(Err.Number) & " was generated by " & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
    If Err.Number <> 0 Then
        MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
    Else
        MsgBox "Success!"
    End If
    Exit Sub
End Sub

最新更新