从一个工作簿中复制列并保存在新工作簿中

时间:2019-06-21 11:18:07

标签: excel vba

这是我第一次使用Stack Overflow,所以我希望我在正确的位置提出这个问题-如果没有的话,我深表歉意。我是使用VBA的完全新手(以前从未编码过任何东西),并且真的很难理解我如何完成以下任务。我读了很多主题,这里有一些我发现的半相关主题:

Excel VBA Copy a Range into a New Workbook https://www.excelcampus.com/vba/copy-paste-another-workbook/

本质上,我正试图找到一种快速的方法:

  • 从一个工作簿(data.xlsx)复制数据(列A和B)。
  • 粘贴到新的工作簿中(作为值)。
  • 另存为CSV文件,文件名取自第三个工作簿(URLs.xlsx)的A列。
  • 重复此过程,从data.xlsx中获取相同的数据(每次粘贴时都会随机化),然后粘贴到新的CSV中-URL.xlsx中有200行,因此最终应该有200个文件。

我尝试过的事情

我尝试过复制代码并替换网络上各种不同文章中的相关组件。它们中的一些有效,但是当我希望添加缺失的部分时,我会不断遇到我不理解的错误。

如果能在这里帮助我的人,我将非常感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

下面是一个避免在新工作簿中粘贴副本的示例:

预期的输入,例如:

具有A1:B200函数的Data.xlsx范围RANDBETWEEN()

enter image description here

URLs.xlsx范围为A1:A200,并带有如下所示的URL:

enter image description here

运行以下代码(在经过计时器测试的计算机上,大约需要1秒钟):

Dim wbData As Workbook, WBurls As Workbook
Dim CSVFileDir As String, CSVVal As String
Dim A As Long, X As Long, Y As Long, Z As Long

Option Explicit

Sub Transfer2CSV()

Set wbData = Workbooks("data.xlsx") 'Make sure it is open upon running macro
Set WBurls = Workbooks("URLs.xlsx") 'Make sure it is open upon running macro

For X = 1 To 200 'Looping through the 200 rows of WBurls
    CSVFileDir = "C:\YourDrive\" & WBurls.Sheets(1).Cells(X, 1).Value & ".csv"
    CSVVal = ""
    A = FreeFile
    Open CSVFileDir For Output As #A
    With wbData.Sheets(1).Range("A1:B200") ' or whichever range you using here
        .Calculate 'Randomize your range again
        For Y = 1 To 200 'or however many rows you have in column A and B.
            For Z = 1 To 2
                CSVVal = CSVVal & .Cells(Y, Z).Value & ","
            Next Z
            Print #A, Left(CSVVal, Len(CSVVal) - 2)
            CSVVal = ""
        Next Y
    End With
    Close #A
Next X

End Sub

输出:

enter image description here

每个文件的外观如下:

enter image description here

答案 1 :(得分:0)

这应该有效。确保您的数据和URLS工作簿已打开。

    @SuppressLint("ValidFragment")
    class MyDemoFragment(private val mainActivity: MainActivity) : Fragment() {

        // EditText declaration
        private lateinit var etMyEditText: EditText

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
            val view = inflater.inflate(R.layout.fragment_my_demo, container, false)

            // EditText initialisation
            etMyEditText = view.findViewById(R.id.etMyEditText)
            // This line will open KeyBoard
            (mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            // Requesting cursor focus   
            etMyEditText.requestFocus()

            return view
        }
    }
相关问题