将变量用作列

时间:2015-11-09 18:50:35

标签: excel vba

我正在制作一个宏来从多个Excel文件中收集数据并将它们组合成一个我可以在同一个图表上绘制它们的数据。

使用变量来显示要粘贴到哪些列的问题。

cq = ColumnLetter(n)
cp = ColumnLetter(n + 1)
Columns("cq:cp").Select

每次循环时n变化3。它一直粘贴CQ和CP列中的所有数据。

我知道这是一个基本问题而且代码很乱,我通常不会使用Excel VBA。

Function ColumnLetter(ByVal intColumnNumber)
        Dim sResult
        intColumnNumber = intColumnNumber - 1
        If (intColumnNumber >= 0 And intColumnNumber < 26) Then
            sResult = Chr(65 + intColumnNumber)
        ElseIf (intColumnNumber >= 26) Then
            sResult = ColumnLetter(CLng(intColumnNumber \ 26)) _
                    & ColumnLetter(CLng(intColumnNumber Mod 26 + 1))
        Else
            Err.Raise 8, "Column()", "Invalid Column #" & CStr(intColumnNumber + 1)
        End If
        ColumnLetter = sResult
End Function

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)
      cq = ColumnLetter(n)
      cp = ColumnLetter(n + 1)
      Columns("A:B").Select
      Selection.Copy
      Windows("Results.xlsx").Activate

      Columns("cq:cp").Select
      ActiveSheet.Paste

    'Change First Worksheet
      wb.Worksheets(1).Range("A1") = ColumnLetter(n)
      wb.Worksheets(1).Range("B1") = Left(myFile, 9)


    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Get next file name
      myFile = Dir
      n = n + 3
  Loop

2 个答案:

答案 0 :(得分:2)

这是一个获取列字母的函数。

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

更改

Columns("cq:cp).Select

Columns(cq & ":" & cp).Select

答案 1 :(得分:2)

Function ColumnLetter(ByVal intColumnNumber)
    ColumnLetter = Replace(Cells(1, intColumnNumber).address(false,false),"1","")
End Function

其余的:

Dim wsRes As Worksheet
Set wsRes = Workbooks("Results.xlsx").Worksheets("sheetNameHere")

Do While myFile <> ""

    Set wb = Workbooks.Open(Filename:=myPath & myFile)

    With wb.Worksheets(1)
        .Range("A:B").Copy wsRes.Cells(1, n)
        .Range("A1").Value = ColumnLetter(n)
        .Range("B1").Value = Left(myFile, 9)
    End With

    wb.Close SaveChanges:=True 'Save and Close Workbook

    'Get next file name
    myFile = Dir
    n = n + 3
Loop